需要简单的SQL查询帮助

时间:2015-11-15 15:07:22

标签: mysql sql

我有这张桌子

uid  |  rid
-----------
1    |    4
1    |   13
2    |    4
3    |   13

我希望我的查询返回uid,其中rid = 13并且没有rid = 4所以结果将是3

到目前为止我已经

SELECT distinct uid
FROM test
WHERE 
ur.rid <> 4 
AND ur.rid = 13

但当然这是返回1和3

我的查询中缺少什么才能获得3?

非常感谢。

1 个答案:

答案 0 :(得分:4)

您可以添加NOT EXISTS

SELECT DISTINCT uid
FROM test t1
WHERE t1.rid = 13
  AND NOT EXISTS (SELECT 1
                  FROM test t2
                  WHERE t2.uid = t1.uid
                    AND t2.rid = 4);

LiveDemo

或使用聚合:

SELECT uid
FROM test
GROUP BY uid
HAVING COUNT(CASE WHEN rid = 13 THEN 1 END) > 0
   AND COUNT(CASE WHEN rid = 4 THEN 1 END) = 0;

LiveDemo2

编辑(由戈登):

上面的答案很好。我只是将其添加为第二个查询的简化(它似乎不适合放入单独的答案,而且评论的时间太长了):

SELECT uid
FROM test
GROUP BY uid
HAVING SUM(rid = 13) > 0 AND
       SUM(rid = 4) = 0;

它利用了MySQL的一个很好的功能。

SqlFiddleDemo