Set random values from an array into database - php

I'm working on a PHP project with MYSQL database. I have a table of groups of students. Each group has an examiner. What i want to do is that i want to set two examiners for each group randomly. How to do it?
MySQL Code:
create table groups (
groupID int(10) not null,
nbStudents int not null,
avgGPA DOUBLE NOT NULL,
projectName varchar(50) not null,
advisorID int,
examiner1ID int,
examiner2ID int,
adminID int not null,
primary key (groupID)
);
create table faculty (
name varchar(30) not null,
facultyID int(10) not null,
email varchar(30) not null,
mobile int(15) not null,
primary key (facultyID)
);
examiner1ID and examiner2ID are foreign keys from the table faculty.

Here is a very convoluted way to do it. It uses 2 subqueries to pick faculty members, and insert .. on duplicate key to update the examiners IDs.
insert into groups
(groupID, examiner1ID, examiner2ID)
select groupID,
#x:=(select facultyID from faculty order by rand() limit 1),
(select facultyID from faculty where facultyID <> #x order by rand() limit 1)
from groups
on duplicate key update examiner1ID=values(examiner1ID), examiner2ID=values(examiner2ID);
#x is a user-defined-variable. In this case, it is used to store the first random faculty member. <> #x makes sure we don't pick the same faculty member in both slots.
Since groupID is a unique key, when we try to insert a row with an existing unique key, it will update the existing row instead of inserting it. That's what on duplicate key update clause is used for.
set different examiners for each group:
insert into groups
(groupID, examier1ID, examier2ID)
select a.groupID, max(if(b.id%2, b.facultyID, 0)), max(if(b.id%2, 0, b.facultyID))
from (
select #row:=#row+1 id, groupID
from groups a
join (select #row:=0) b) a
join (
select #row:=#row+1 id, facultyID
from (
select facultyID
from faculty a
order by rand()) a
join (select #row:=0) b) b on a.id = ceil(b.id/2)
group by a.groupID
on duplicate key update examiner1ID=values(examiner1ID), examiner2ID=values(examiner2ID);

Related

How can i combine two selects from two tables?

This is my DB schema:
CREATE TABLE `members` (
`m_id` int NOT NULL AUTO_INCREMENT,
`m_name` varchar(355),
`m_email` varchar(20) UNIQUE,
PRIMARY KEY (`m_id`)
);
CREATE TABLE `schools` (
`s_id` int NOT NULL AUTO_INCREMENT,
`s_name` varchar(355)
);
CREATE TABLE `schools_members` (
`sm_id` int NOT NULL AUTO_INCREMENT,
`sm_school_id` int NOT NULL,
`sm_member_id` int NOT NULL,
FOREIGN KEY (sm_school_id) REFERENCES schools(s_id),
FOREIGN KEY (sm_member_id) REFERENCES members(m_id)
);
I need to display all members for a selected school by a given school id ($schoolId). So i assume that the query will touch on schools_members and members.
I believe the logic is: select all the sm_member_id where sm_school_id = $schoolId from table schools_members and then SELECT m_name and
m_email for each m_id (member id) from table members that is IN the last query result.
This is not required, but now im curious if i want to join to this result the s_name (school name) from table schools so that each member displays the name of school also?
You could just use a join between schools_members and members
select m.m_name, m.m_email
from schools_members sm
inner join members m ON m.m_id = sm.sm_member_id
where sm.sm_school_id = Your_value
and for school name
select m.m_name, m.m_email, s.s_name
from schools_members sm
inner join members m ON m.m_id = sm.sm_member_id
inner join schools s on s.s_id = sm.sm_school_id
where sm.sm_school_id = Your_value

How to check if values from the table 1 are used in table 2?

I have two tables employees and departments.
Departments:
create table dept (
id INT NOT NULL AUTO_INCREMENT,
dept_name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
Employees:
create table department_master (
id INT NOT NULL AUTO_INCREMENT,
dept_id INT NOT NULL,
emp_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
I want to prevent departments being deleted from the UI if they are assigned to one of the employees in employee table. Left join is giving me duplicate values.
How do I see if the departments are being used in the employees table.
If you want to prevent a department from being deleted, you can simply add a foreign constraint to the table department_master for dept_id column.
create table department_master (
id INT NOT NULL AUTO_INCREMENT,
dept_id INT NOT NULL,
emp_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id),
constraint con_dm foreign key dept_id references dept( id )
);
It's default behavior is ON DELETE RESTRICT which means that if there is atleast one row present in the department_master for a given dept_id, it can't be deleted from dept table.
If you want to fetch, the department that don't have any employee record, you can use NOT EXISTS:
select *
from dept d
where not exists (
select 1
from department_master m
where d.id = m.dept_id
);
I believe you want a count of the number of employees grouped by the department, like so:
SELECT count(*) as employees, d.dept_name FROM dept AS d LEFT JOIN department_master AS e ON e.dept_id = d.id group by e.dept_id

Three tables inner join

I have three tables "user" , "bidding" and "item".
I need to find the query in order to get the completed item auctions for a buyer. The way how to find this in my database is the following, item.received=1 AND u.userid=X (this X will be filled in from my PHP which gives the userID of the highest bid). (note that received=1 implies that the deadline is over so this check is not necessary anymore).
Short explanation of the system: it is an auction website, where a user places bids on items and on the users personal account page I want to show the amount of auctions which he bought (and are processed, thus completed).
The 3 tables look like this:
CREATE TABLE user (
userid INT NOT NULL AUTO_INCREMENT,
username CHAR(30) NOT NULL UNIQUE,
password CHAR(32) NOT NULL,
firstname CHAR(30) NOT NULL,
lastname CHAR(30) NOT NULL,
gender CHAR(1) NOT NULL,
email CHAR(50) NOT NULL UNIQUE,
birthdate DATE NOT NULL,
addressid INT NOT NULL,
picture CHAR(50),
lastlogin TIMESTAMP NOT NULL,
role CHAR(30),
paymentid INT NOT NULL,
PRIMARY KEY (userid),
FOREIGN KEY (addressid)
REFERENCES address(addressid),
FOREIGN KEY (paymentid)
REFERENCES payment(paymentid)
);
CREATE TABLE item (
itemid INT NOT NULL AUTO_INCREMENT,
name CHAR(40) NOT NULL,
description CHAR(255) NOT NULL,
originalpurchasedate DATE,
deadline TIMESTAMP NOT NULL,
minprice DOUBLE,
received BOOLEAN NOT NULL,
dateadded TIMESTAMP NOT NULL,
openbidding BOOLEAN NOT NULL,
categoryid INT NOT NULL,
ownerid INT NOT NULL,
PRIMARY KEY (itemid),
FOREIGN KEY (categoryid)
REFERENCES category(categoryid),
FOREIGN KEY (ownerid)
REFERENCES user(userid)
);
CREATE TABLE bidding (
userid INT NOT NULL,
itemid INT NOT NULL,
amount DOUBLE,
bidtime TIMESTAMP NOT NULL,
FOREIGN KEY (userid)
REFERENCES user(userid),
FOREIGN KEY (itemid)
REFERENCES item(itemid)
);
The malfunctioning solution I have already is: the result is 3 rows and results being: 3 , 1 , 5. The solution I expect to get only has to be 1 row, containing the number of distinct items.
SELECT DISTINCT COUNT(u.userid) FROM `item` i
INNER JOIN `bidding` b ON i.itemid = b.itemid
INNER JOIN `user` u ON b.userid = u.userid
WHERE i.received=1 AND u.userid=2
GROUP BY i.itemid
You need to change your query to group on userid instead of item id, and count different items instead of different users.
SELECT DISTINCT COUNT(i.itemid) FROM `item` i
INNER JOIN `bidding` b ON i.itemid = b.itemid
INNER JOIN `user` u ON b.userid = u.userid
WHERE i.received=1 AND u.userid=2
GROUP BY u.userid

MYSQL: How to find out the qty of unequipped items?

Here is my DB Structure:
CREATE TABLE IF NOT EXISTS `UserItems` (
`id` bigint(20) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL,
`item_id` int(10) unsigned NOT NULL,
`qty` int(11) NOT NULL default '0'
) ;
CREATE TABLE IF NOT EXISTS `UserEquippedItems` (
`user_id` int(10) unsigned NOT NULL,
`user_item_id` bigint(20) unsigned NOT NULL
);
CREATE TABLE IF NOT EXISTS `UserFriendEquippedItems` (
`user_friend_id` int(10) unsigned NOT NULL,
`user_item_id` bigint(20) unsigned NOT NULL
);
UserItems keeps all the item inventory with quantity.
let say if I have 5 item (item id 123456). then the entry will be
(null, $userid, 123456, 5).
the qty is the quantity of all the entity with the same item_id.
However, some Users may equip the item. Some do not. If they equip it, it will be an entry in UserEquippedItems table.
Also, users' friends can equip the user's item too.
Sample Data:
UserItems:
id, user_id, item_id, qty
( 1, 4567, 123123123, 5)
( 2, 4567, 100010001, 2)
( 3, 4567, 100010099, 1)
UserEquippedItems: (user_item_id is UserItems.id)
user_id, user_item_id
( 4567, 1)
( 4567, 2)
UserFriendEquippedItems
(user_item_id is UserItems.id)
user_friend_id, user_item_id
( 4100, 1)
( 4100, 3)
So, how can I find out the quantity of items that are equipped?
and how can I find out the quantity of items that are NOT equipped ?
Side Story: Before, we have each individual UserItems as a single entry in the DB. e.g. for item_id = 123123123, if I have 5 of them, i have 5 entries in the DB. But then, our DB grows like crazy to 4 million UserItems records. that's why instead of having 5 entries, we only have one entry in the UserItems table, with the qty field for keep track how many in total. I don't know if it is the right approach, but I hope it can cut down 75% of the DB size.
Also, it was the query to get the unequipped items:
SELECT Items.id, count(UserItems.id) as numCount
FROM UserItems INNER JOIN
Items ON UserItems.active=1 AND
UserItems.item_id=Items.id AND
Items.active=1 AND
UserItems.user_id=$userId
WHERE NOT EXISTS (
SELECT UserEquippedItems.user_item_id
FROM UserEquippedItems
WHERE UserEquippedItems.user_item_id= UserItems.id
)
AND NOT EXISTS (
SELECT UserFriendsEquippedItems.user_item_id
FROM UserFriendsEquippedItems
WHERE UserFriendsEquippedItems.user_item_id= UserItems.id)
GROUP BY Items.id
Of course, this query doesn't work with the new schema. :)
This should work:
SELECT id, user_id, item_id, qty,
(SELECT COUNT(*) FROM UserEquippedItems uei
WHERE uei.user_item_id=ui.id) as qty_equipped,
(SELECT COUNT(*) FROM UserFriendEquippedItems ufei
WHERE ufei.user_item_id=ui.id) as qty_friend_equipped
FROM UserItems ui
Then to get the unequipped, on your client you can subtract the qty_equipped and qty_friend_equipped from qty.
A single query that just returns unequipped:
SELECT id, user_id, item_id, qty,
qty-
(SELECT COUNT(*) FROM UserEquippedItems uei
WHERE uei.user_item_id=ui.id)-
(SELECT COUNT(*) FROM UserFriendEquippedItems ufei
WHERE ufei.user_item_id=ui.id)
as qty_unequipped
FROM UserItems ui
You could combine those 2 queries above into one big query, but I image that would hurt performance, since it will run the sub-queries twice.
You can add a WHERE clause on the end of both of these to return results for a specific user / item.
To count the total number of items equipped:
SELECT count(*) FROM UserEquippedItems e JOIN UserItems i ON (i.id = e.user_item_id)
To find the total number of items of id $item_id equipped
SELECT count(*) FROM UserEquippedItems e WHERE e.user_item_id = $item_id
And to find the total number of items user $user_id has equipped (my first response, though probably not what you're after)
SELECT count(*) FROM UserEquippedItems WHERE user_id = $user_id

How can I join in data from a key : value meta table in mysql?

Say I have three tables in my database:
CREATE TABLE `users` (
`user_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR(16) NOT NULL
);
CREATE TABLE `users_meta` (
`meta_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_id` INT NOT NULL ,
`key` VARCHAR(200) NOT NULL ,
`value` TEXT NOT NULL
);
CREATE TABLE `posts` (
`post_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_id` INT NOT NULL ,
`content` TEXT NOT NULL
);
The table users_meta is just a key-value store of information about users, such that we can add any piece of information we want.
Say I added a key => value pair to the users_meta table for each user where the key was "age", and the value was a number representing their age.
Given this set of circumstances, what's the best way to select the first 10 posts ordered by user age?
I like putting the condition of the join in the join itself to be clear that I want a limited join:
SELECT p.post_id, p.content
FROM users u
INNER JOIN users_meta um
ON (u.user_id = um.user_id) AND um.key = 'age'
INNER JOIN posts p
ON (p.user_id = u.user_id)
ORDER BY um.value
limit 10
If you order by user age only, you will select 10 posts of the same user (the youngest one).
I would suggest to denormalize and store age in users table directly.
Agree with #KOHb, but if that's exactly what you want, here is the query:
SELECT TOP 10 p.id, p.content
FROM users u JOIN users_meta um ON (u.user_id = um.user_id)
JOIN posts p ON (p.user_id = u.user_id)
WHERE um.key = 'age'
ORDER BY um.value

Categories