1

我有以下查询来检索对特定问题“”对另一个问题回答“是”的客户。

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

哪个工作正常。但是,我希望更改查询以检索对特定问题“”对另一个问题回答“否”的客户。

关于如何实现这一目标的任何想法?

PS - 上表的响应是 EAV 格式,即。一行代表一个属性而不是一列。

4

2 回答 2

3

我假设您的响应表中有一个名为 customer_id 的列。尝试将响应表加入自身:

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'
于 2010-07-17T15:39:57.867 回答
0

大概是这样的:

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')

我对缺失的join条件做了一个假设,修改为适合您的模式。

于 2010-07-17T15:38:07.197 回答