如何根据3个关系选择桌面上的项目?

时间:2013-08-23 11:11:36

标签: mysql sql laravel laravel-4

我有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','red'为'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

2 个答案:

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

但是,我不太确定这与问题开头的表格有什么关系。您的代码示例和数据布局不一致。

答案 1 :(得分: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。