2015-11-07 101 views
1

我正在開發訂單的分配功能,並且我試圖將訂單分配給具有最少未決請求的用戶。我想獲得用戶ID,其中掛起的值是所有用戶中最少的。從其中單列爲MIN的列中選擇一個SQL值()

實施例:

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

'ORDER BY未決ASC',比限1 – Terminus

+0

我thinl你可以有多個,其實,不是嗎? –

+0

如果有2位用戶0等待處理,會發生什麼情況?選擇全部還是隻有一個? –

回答

0

您可以訂購通過列結果待定(見註釋由西蒙·尼格羅的查詢)。使用限制字,在結果中,您將只獲得第一行,在這種情況下,您將得到最小未決值的結果。

我現在看到亞歷山大Miladinovic的情況下,如果表中有與相同值很多行掛起:你可以執行:

  1. 查詢來獲取的的mininium值待定
  2. 使用在先前步驟中獲得的值與該值接收的行

    SELECT USER_ID FROM writerdata_tb WHERE未決=(SELECT MIN(待定)FROM writerd ata_tb)

+0

我記得閱讀嵌套查詢的東西,我假設如果我使用LIMIT它應該只返回從我使用的任何方法只有一個值?如果選擇所有用戶並按掛起的值升序排列,並且使用第一個用戶的值,那麼它會更容易嗎? – trecoolable

0

試試這個方法:從writerdata_tb中選擇userID,其中pending =(從writerdata_tb選擇min(pending));

0

如果重複

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 
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 
相關問題