2013-08-30 25 views
1

這是我的第一個問題。我搜索了很多文檔,但找不到答案。
我有3張桌子。在MySQL中使用多個OR/AND進行篩選

product_main(with idx and name)<br /> 
proudct_attributes (with idx 'pid gid value)<br /> 
product_attributes_groups (with idx name) <br /> 

現在我試圖按屬性過濾產品。我有一個單獨的屬性沒有問題,但我不能讓它工作與幾個條件,即(紅色或藍色的,但只有新)過濾

SELECT `pid` FROM `product_attributes` 
LEFT JOIN `product_main` ON `product_attributes`.`pid` = `product_main`.`idx` 
LEFT JOIN `product_attributes_groups` ON `product_attributes`.`gid` = `product_attributes_groups`.`idx` 
WHERE 
    (
    (`product_attributes_groups`.`name` = 'color' AND `product_attributes`.`value` ='red') 
    OR 
    (`product_attributes_groups`.`name` = 'color' AND `product_attributes`.`value` ='blue') 
) 
    AND 
    (`product_attributes_groups`.`name` = 'condition' AND `product_attributes`.`value` ='new') 

編輯:

這幫助: 選擇pmidx from product_attributes as pa join product_main as pm on papid = pmidx加入 product_attributes_groups as pig on pagid = pigidx 組由pm組成。 idx具有 總和(pigname = '顏色' AND pavalue在( '紅', '藍'))> 0和 總和(pigname = '狀態' AND pavalue = '使用')> 0;

通過Gordon,稍作修改。

+0

而你的問題是? – hakre

+0

這是EAV嗎?一般來說,我避免像瘟疫一樣的EAV。在我不得不使用它的地方,我更喜歡構建一個僞歸一化的「物化視圖」,然後將所需的條件附加到該視圖上。 – Strawberry

回答

0

你有一個「設置中集」查詢,在那裏你正在努力尋找一個組內的比賽(產品屬性)。我喜歡聚集和一個having子句來解決這些:

select pm.pid 
from product_attributes pa join 
    product_main pm 
    on pa.`pid` = pm.`idx` join 
    product_attributes_groups pig 
    on pm.`gid` = `pig`.`idx` 
group by pm.pid 
having sum(pig.`name` = 'color' AND `pa`.`value` in ('red' , 'blue')) > 0 and 
     sum(pig.`name` = 'condition' AND pa.`value` ='new') > 0; 

having子句中每個條件正在計數的行數爲匹配一個條件,每個pid

+0

的優雅解決方案,但這一點很有幫助。謝謝戈登:) – LordKarp

0

WHERE 
    `product_attributes_groups`.`name` = "something" 
    AND `product_attributes_groups`.`name` = "something else" 

的條件永遠是正確的。檢查你想要做什麼並重寫你的過濾器。

+0

我有不同'product_attributes_groups'.'name'值的多行,與'product_attributes'.'value'相同我想選擇所有新產品,但可能是藍色或紅色。 – LordKarp

+0

然後,您需要在同一張表上再次「加入」,使用別名。 – Halcyon

0

試試這個。它應該與組合(名稱和(紅色或藍色))OR(條件和新的)工作

SELECT `pid` FROM `product_attributes` 
LEFT JOIN `product_main` ON `product_attributes`.`pid` = `product_main`.`idx` 
LEFT JOIN `product_attributes_groups` ON `product_attributes`.`gid` = `product_attributes_groups`.`idx` 
WHERE 
    (`product_attributes_groups`.`name` = 'color' AND (`product_attributes`.`value` ='red' OR `product_attributes`.`value` ='blue')) 
    OR 
    (`product_attributes_groups`.`name` = 'condition' AND `product_attributes`.`value` ='new') 
+0

這將返回所有新舊產品。我希望它只返回新的。 Thx幫助tho :) – LordKarp

+0

@LordKarp。是的,這是有道理的;)你是否嘗試過:(名字AND(紅色或藍色))AND(條件AND新)。儘管我喜歡GordonLinoff使用HAVING –