繁体   English   中英

如何在mysql中选择匹配“多行条件”的行

[英]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"))

但它会返回其他绿色或汽车的产品。 将其更改为and也不会返回任何内容。

我希望收到的是product_id: 1color: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

请参阅演示
结果:

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

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

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%'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM