的Postgres
我有表user_answers:
----------------------------
| id | user_id | answer_id |
----------------------------
| 1 | 47 | 121 |
----------------------------
| 2 | 47 | 125 |
----------------------------
| 3 | 47 | 141 |
----------------------------
| 4 | 49 | 122 |
----------------------------
| 5 | 49 | 121 |
----------------------------
| 6 | 49 | 101 |
----------------------------
| 7 | 52 | 121 |
----------------------------
| 8 | 52 | 125 |
----------------------------
| 9 | 52 | 101 |
----------------------------
| 10 | 67 | 101 |
----------------------------
我想获得user_id,只有user_id,其中answer_id = 121且answer_id = 125。
结果很好:47和52 因为: user_id = 49有121,但没有125
这个简单的查询不起作用(不返回任何内容):
SELECT user_id FROM user_answers
WHERE answer_id = 121 AND answer_id = 125
答案 0 :(得分:2)
select user_id
from user_answers
where answer_id in (121, 125)
group by user_id
having count(*) = 2
答案 1 :(得分:2)
您的查询不返回任何内容,因为answer_id
在任何给定行上只有一个值。它不能在行上有多个值。
这是set-within-sets查询的示例。我建议您使用group by
和having
。这是一种方法:
SELECT user_id
FROM user_answers
WHERE answer_id IN (121, 125)
GROPU BY user_id
HAVING COUNT(DISTINCT answer_id) = 2;
这将返回具有121,125和其他值的值。只获得这两个值:
SELECT user_id
FROM user_answers
WHERE answer_id IN (121, 125)
GROPU BY user_id
HAVING SUM(CASE wHEN answer_id = 121 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE wHEN answer_id = 125 THEN 1 ELSE 0 END) > 0;
答案 2 :(得分:0)
你需要或不是和。
SELECT user_id FROM user_answers WHERE (answer_id = 121 OR answer_id = 125)
您的原始查询正在查找answer_id同时为121和125的结果。使用OR查找answer_id为值的结果。