我有这张桌子
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?
非常感谢。
答案 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
强>