2012-11-07 96 views
-1

我的請求似乎並不那麼困難,但我不確定最好的方式來做到這一點。MySQL SELECT如果只匹配一個值

我有如下表:

userID file 
    1  1 
    1  2 
    1  3 
    2  1 
    2  3 
    3  2 
    4  1 
    4  2 

,我想選擇用戶標識符,只有有文件號碼2.在我的例子,結果將只有3

+0

謝謝,我會測試不同的解決方案 – MamaWalter

回答

5
SELECT userID 
FROM tableName a 
WHERE file = 2 
GROUP BY userID 
HAVING COUNT(*) = 
(
    SELECT COUNT(*) 
    FROM tableName b 
    WHERE a.userID = b.userID 
) 
1

你可以使用WHERE NOT EXISTSSQL Fiddle):

SELECT UserId 
FROM theTable t 
WHERE file = 2 
AND NOT EXISTS(SELECT 1 FROM theTable tt WHERE t.UserId = tt.UserId AND file <> 2) 
GROUP BY UserId 

或自反連接(SQL Fiddle):

SELECT t.UserId 
FROM theTable t 
LEFT OUTER JOIN theTable tt ON t.UserId = tt.UserId AND tt.file <> 2 
WHERE t.file = 2 
AND tt.UserId IS NULL 
GROUP BY t.UserId 
+0

嗯,爲什麼downvote?兩個例子都能產生正確的結果。 –

0

嘗試此查詢 -

SELECT userID FROM table 
GROUP BY userID 
HAVING COUNT(IF(file = 2, 1, NULL)) = COUNT(*) 

+--------+ 
| userID | 
+--------+ 
|  3 | 
+--------+ 
0

一種方式是通過一個標誌,如果他們有另外一個2號文件,總的標誌記錄爲用戶...如果兩個= 1,那麼你很好。但是,該版本查詢所有用戶。

select 
     userID 
    from 
     YourTable 
    group by 
     UserID 
    having 
      sum(if(file = 2, 1, 0)) = 1 
     AND count(*) = 1 

此版本適用於預查詢只列出這些人誰至少有一個2號文件,然後獲取總數

select 
     PreQuery.UserID 
    from 
     (select distinct YT1.userID 
      from YourTable YT1 
      where YT1.File = 2) as PreQuery 
     JOIN YourTable YT2 
     on PreQuery.UserID = YT2.UserID 
    group by 
     PreQuery.UserID 
    having 
     count(*) = 1 

我顯然不知道你的數據大小(記錄計數),但如果您有10k個用戶和100k個文件,但只有250個可以訪問文件#2,那麼這個第二個查詢將只關注250個用戶,然後只提取那些只有那個單一顯式HAVING count = 1的文件庫。

相關問題