从列中选择一个SQL值,其中单独的列为MIN()

时间:2015-11-07 20:51:57

标签: php mysql mysqli min

我正在为订单开发一个赋值函数,我正在尝试将订单分配给具有最少待处理请求的用户。我想获取用户ID,其中pending的值是所有用户中最少的。

示例:

userID    pending
------    -------
0         3
1         0 <----This user has the least pending of all
2         4

如何设置SQL查询以返回表中待处理请求数最少的用户ID?

$sql="SELECT user_id FROM writerdata_tb WHERE pending = '//Minimum pending here//' LIMIT 1";
$assign = $conn->query($sql);
$row = $assign->fetch_assoc();

4 个答案:

答案 0 :(得分:1)

对所提出的各种可能答案的比较:

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

答案 1 :(得分:0)

您可以按列待处理订购结果(请参阅Simone Nigro对查询的评论)。使用 limit 字,在结果中您将只获得第一行,在这种情况下,您将获得minium挂起值的结果。

我现在看到Aleksandar Miladinovic的情况,如果表中有许多行具有相同的值待定:您可以执行:

  1. 获取待处理
  2. 的mininium值的查询
  3. 使用上一步中获取的值来接收具有该值的行

    SELECT user_id FROM writerdata_tb WHERE pending =(SELECT min(pending)FROM writerdata_tb)

答案 2 :(得分:0)

尝试这种方式:从writerdata_tb中选择userID,其中pending =(从writerdata_tb中选择min(pending));

答案 3 :(得分:0)

如果重复用户ID

SELECT
    t.userID
from 
    tasks as t
group by (t.userID)
order by sum(pending) asc 
limit 1

否则

SELECT
    t.userID
from 
    tasks as t
order by pending asc 
limit 1