I have the following query to retrieve customers who answer YES to a particular question "OR" NO to another question.
SELECT customers.id
FROM customers, responses
WHERE (
(
responses.question_id = 5
AND responses.value_enum = 'YES'
)
OR (
responses开发者_运维百科.question_id = 9
AND responses.value_enum = 'NO'
)
)
GROUP BY customers.id
Which works fine. However I wish to change the query to retrieve customers who answer YES to a particular question "AND" answer NO to another question.
Any ideas on how I can achieve this?
PS - The responses above table is in an EAV format ie. a row represents an attribute rather than a column.
I'm assuming that you have a column called customer_id in your responses table. Try joining the responses table to itself:
SELECT Q5.customer_id
FROM responses Q5
JOIN responses Q9 ON Q5.customer_id = Q9.customer_id AND Q9.question_id = 9
WHERE Q5.question_id = 5
AND Q5.value_enum = 'YES'
AND Q9.value_enum = 'NO'
Approximately as such:
SELECT distinct
c.id
FROM
customers c
WHERE
exists (select 1 from responses r where r.customer_id = c.id and r.response_id = 5 and r.value_enum = 'YES')
and exists (select 1 from responses r2 where r2.customer_id = c.id and r2.response_id = 9 and r2.value_enum = 'NO')
I made an assumption on the missing join
condition, modify as correct for your schema.
精彩评论