0

我有 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.

4

2 回答 2

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;

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

于 2013-08-23T11:14:36.083 回答
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。

于 2013-08-23T12:11:06.583 回答