MYSQL查询帮助(EAV表)

时间:2010-07-17 15:32:45

标签: mysql entity-attribute-value

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

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

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

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

PS - 上表中的答案采用EAV格式,即。一行表示属性而不是列。

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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条件做了一个假设,修改为你的架构正确。