我有一个包含一些数据的表数据。多个行属于具有相同customer_id的同一客户(Customers表的索引)。该客户已经回答了一些他们有问题的问题(问题表的索引)。在数据表中,还有关于客户对question0
的回答的值列我正在尝试选择对于question_id 1,2,3的答案为0的customer_id
我也试过
SELECT distinct customer_id
FROM Data
WHERE value = 0
AND question_id IN (1, 2, 3);
但是我没有得到适当的结果 24 ,这是客户的customer_id,对question_id 1,2和3的问题回答0。
答案 0 :(得分:1)
你很亲密。您可以使用group by
和having
获得所需内容:
SELECT customer_id
FROM Data
WHERE value = 0 AND question_id IN (1, 2, 3)
GROUP BY customer_id
HAVING COUNT(DISTINCT question_id) = 3;
HAVING
子句指定回答所有三个问题 - 答案为0
。
答案 1 :(得分:1)
GROUP BY
和 HAVING
的另一种方法。
<强>查询强>
select `customer_id`
from `your_table_name`
where `question_id` in (1,2,3)
group by `customer_id`
having sum(`value`) = 0;
<强> Find a demo here 强>