I am developing an assignment function for orders and I am trying to assign the order to a user who has the least pending requests. I want to get the user id where the value for pending is the least of all of the users.
Example:
userID pending
------ -------
0 3
1 0 <----This user has the least pending of all
2 4
How do I set up an SQL Query to return the user ID with the least amount of pending request of the table?
$sql="SELECT user_id FROM writerdata_tb WHERE pending = '//Minimum pending here//' LIMIT 1";
$assign = $conn->query($sql);
$row = $assign->fetch_assoc();
A comparison of various possible answers proposed:
EXPLAIN SELECT aa.userId, aa.pending
FROM writerdata_tb AS aa
INNER JOIN writerdata_tb AS bb
ON aa.userId = bb.userId
WHERE aa.pending >= bb.pending
ORDER BY aa.pending ASC
LIMIT 1;
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE aa ALL PRIMARY NULL NULL NULL 4 Using temporary; Using filesort
1 SIMPLE bb ALL PRIMARY NULL NULL NULL 4 Using where; Using join buffer (Block Nested Loop)
EXPLAIN SELECT userId, pending
FROM writerdata_tb
WHERE pending = (
SELECT MIN(pending)
FROM writerdata_tb
);
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY writerdata_tb ALL NULL NULL NULL NULL 4 Using where
2 SUBQUERY writerdata_tb ALL NULL NULL NULL NULL 4 NULL
EXPLAIN SELECT userId, pending
FROM writerdata_tb
ORDER BY pending ASC
LIMIT 1;
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE writerdata_tb ALL NULL NULL NULL NULL 4 Using filesort
EXPLAIN SELECT t.userId
FROM writerdata_tb AS t
GROUP BY (
t.userId
)
ORDER BY SUM(pending) ASC
LIMIT 1;
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t index PRIMARY PRIMARY 4 NULL 4 Using temporary; Using filesort
You can order results by column pending (see comment by Simone Nigro for the query). Using the limit word, in the result you will get only the first row, in this case you will get the result with minium pending value.
I see now the case of Aleksandar Miladinovic, if in the table there are many rows with same value of pending : you can execute:
Use the value obtained in the previous step to receive the rows with that value
SELECT user_id FROM writerdata_tb WHERE pending=(SELECT min(pending) FROM writerdata_tb)
尝试这种方式:从writerdata_tb中选择userID,其中未决=(从writerdata_tb中选择min(pending));
If UserID's are repeated
SELECT
t.userID
from
tasks as t
group by (t.userID)
order by sum(pending) asc
limit 1
else
SELECT
t.userID
from
tasks as t
order by pending asc
limit 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.