如何 select 与 mysql 中的 "multiple rows condition" 匹配的行

How to select rows that matches "multiple rows condition" in mysql

所以我创建了一个 sql fiddle 来更清楚地解释我的问题:

http://sqlfiddle.com/#!9/f35416

如您所见,我有 3 个表,其中 1 个链接另外 2 个。

table name: tags
---------------------
id | tag      | value
---------------------
1  | color    | green
2  | color    | yellow
3  | color    | red
4  | category | dress
5  | category | car

table name: product_tags_link
---------------------
product_id | tag_id
---------------------
1          | 1
1          | 5
2          | 1
3          | 2
3          | 5
4          | 4
5          | 4
5          | 1

table name: products
---------------------
id  | name
---------------------
1   | green car
2   | yellow only
3   | yellow car
4   | dress only
5   | green dress

如果我能得到任何具有“颜色”“绿色”和“类别”“汽车”的产品,我该怎么做?

我试过:

select `ptl`.`product_id` 
from `product_tags_link` as `ptl`
    inner join `tags` on `tags`.`id` = `ptl`.`tag_id`
where ((`tags`.`tag` = "green") or (`tags`.`value` = "car"))

但它会 return 其他绿色产品或汽车。将其更改为 and 也不会 return 任何东西。

我希望收到的是 product_id: 1,它同时具有 color:greencategory:car

加入所有 3 个表,按产品分组并在 HAVING 子句中设置条件:

select p.id, p.name 
from products p
inner join product_tags_link l on l.product_id = p.id
inner join tags t on t.id = l.tag_id
where (t.tag = 'category' and t.value = 'car')
   or (t.tag = 'color' and t.value = 'green')
group by p.id, p.name
having count(distinct t.tag) = 2

或者:

select p.id, p.name 
from products p
inner join product_tags_link l on l.product_id = p.id
inner join tags t on t.id = l.tag_id
where (t.tag, t.value) in (('category', 'car'), ('color', 'green'))
group by p.id, p.name
having count(distinct t.tag) = 2

参见demo
结果:

> id | name
> -: | :---
>  1 | test

我会省略连接 table 并按如下方式进行简单连接:

SELECT 
    p.id AS product_id
FROM
    products p
        LEFT JOIN
    tags t ON p.id = t.id
WHERE
    t.value = 'green'
        AND p.name LIKE '%car%'