2013-08-23 71 views
0

我有3個表:如何根據3關係選擇表格上的項目?

Categories 
| id | name 
| 1 | Samsung 
| 2 | Apple 


Products 
| id | category_id | name 
| 1 | 1   | Galaxy S4 
| 2 | 1   | Galaxy S3 
| 3 | 1   | SHG-G600 
| 4 | 3   | Lumia 920 


Tags 
| id | product_id | name   | type 
| 1 | 1   | smart-phone | phoneType 
| 2 | 2   | smart-phone | phoneType 
| 3 | 3   | normal-cell | phoneType 
| 4 | 1   | red   | phoneColor 

我試圖找到一種方法來選擇具有「智能手機」爲「PHONETYPE」和「紅」爲「phoneColor」三星所有設備。

所以這就是我所做的到現在爲止:

SELECT * 
FROM `products` 
INNER JOIN `product_tag` ON `product_tag`.`product_id` = `products`.`id` 
INNER JOIN `tags` ON `tags`.`id` = `products`.`id` 
WHERE (
     `tags`.`type` = 'phoneType' 
     AND `tags`.`name` = 'smart-phone' 
    ) 
OR (
     `tags`.`type` = 'phoneColor' 
     AND `tags`.`name` = 'red' 
    )  
) 

這沒有工作的是(不選擇類別)。我也不知道如何加入類別並添加where categories.id = 1

回答

1

您可以通過將邏輯放在having子句中來實現。對於您的示例代碼:

SELECT p.* 
FROM `products` p join 
    `product_tag` pt 
    ON pt.`product_id` = p.`id` join 
    `tags` t 
    ON t.`id` = p.`id` 
group by p.id 
having sum(t.`type` = 'caseMaterial' AND t.name = 'leather') > 0 and 
     sum(t.`type` = 'caseFor' AND t.`name` = 'iphone-5') > 0; 

但是,我不太確定這與問題開始時的表如何相關。您的代碼示例和數據佈局不一致。

+0

這是行不通的,我不得不改變這一行:ON t.'''' p.'''到ON t.''''' pt.'tag_id'。 但是,謝謝你!第一個難題就解決了 –

0

我通過添加類別連接擴展了@Gordon Linoff的解決方案。

SELECT p.* 
FROM `products` p join 
    `categories` c 
    ON c.`id` = p.`category_id` join 
    `product_tag` pt 
    ON pt.`product_id` = p.`id` join 
    `tags` t 
    ON t.`id` = pt.`tag_id` 
where c.id = 1 
group by p.id 
having sum(t.`type` = 'phoneType' AND t.name = 'smart-phone') > 0 and 
     sum(t.`type` = 'phoneColor' AND t.`name` = 'red') > 0 

這是現在工作。感謝@Gordon Linoff。

相關問題