2010-07-17 66 views
1

我有以下查詢來檢索對特定問題「」回答「YES」的客戶是否有其他問題。MYSQL查詢幫助(EAV表)

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 

這工作正常。但是,我希望更改查詢以檢索對特定問題「」回答「YES」的客戶,對另一個問題回答「否」。

關於我如何實現這一點的任何想法?

PS - 上表中的響應採用EAV格式,即。一行代表一個屬性而不是一列。

+0

查詢如何在沒有連接條件的情況下工作?也許你可以發佈你的表定義? – 2010-07-17 15:35:15

+0

在您的示例中,您似乎並未加入客戶和響應表。這會產生笛卡兒的結果,就像你寫的那樣 - 這是故意的嗎? – Tom 2010-07-17 15:37:15

+0

難道你不能只是將OR更改爲AND – webdad3 2010-07-17 15:39:31

回答

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' 
+0

+1這比我想要做的要簡單得多。尼斯。 – northpole 2010-07-17 15:44:20

+0

是的,對我來說,Donnie的查詢返回相同的結果。這裏的幫助很大,不能夠感謝你。 – 8bitreboot 2010-07-17 15:59:00

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條件作出的假設,修改您的模式是正確的。