Select products from tag group or other which are not in group

时间:2018-04-28 17:54:59

标签: mysql

How select products which has tag red in tag_group color or product which does NOT have tag_group color? Expected result is on bottom.


SQL Fiddle: http://sqlfiddle.com/#!9/2caf6a/1

SELECT product.name
FROM product
INNER JOIN product_tag ON product.id = product_tag.product_id
INNER JOIN tag ON product_tag.tag_id = tag.id
INNER JOIN tag_group ON tag.tag_group_id = tag_group.id
WHERE (tag_group.name = 'color' AND tag.name = 'red') OR ...

我尝试了什么

... tag_group.name != 'color'

或者

... product_tag.tag_id NOT IN (1,2,3)

但它返回红宝石,水晶,祖母绿,因为

模式

enter image description here

数据

产品

+---------------+
| id | name     |
+---------------+
| 1  | ruby     |
| 2  | emerald  |
| 3  | sapphire |
| 3  | crystal  |
+---------------+

product_tag

+------------+--------+
| product_id | tag_id |
+------------+--------+
|          1 |      1 |
|          2 |      2 |
|          3 |      3 |
|          4 |      4 |
|          2 |      4 |
+------------+--------+

标签

+----+-------+--------------+
| id | name  | tag_group_id |
+----+-------+--------------+
|  1 | red   |            1 |
|  2 | green |            1 |
|  3 | blue  |            1 |
|  4 | new   |            2 |
+----+-------+--------------+

tag_group

+----+--------+
| id |  name  |
+----+--------+
|  1 | color  |
|  2 | ribbon |
+----+--------+

预期结果:

+---------+
|  name   |
+---------+
| ruby    |
| crystal |
+---------+

0 个答案:

没有答案