MySQL SELECT如果仅匹配一个值

时间:2012-11-07 15:39:49

标签: mysql select

我的要求似乎并不那么困难,但我不确定最好的方法。

我有下表:

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

我想选择具有文件编号2的UserID。在我的示例中,结果仅为3.

4 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分:0)

尝试此查询 -

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

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

答案 3 :(得分:0)

一种方法是通过一个标志IF的标志,除了用户的总记录外,他们还有一个#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的单一显式文件库的那些。