[英]MySql - how to select rows from one table based on multiple values joined in another table
I have two tables, one of products, and the other of product tags我有两张表,一张是产品,另一张是产品标签
CREATE TABLE IF NOT EXISTS `products` (
`id` int(6) unsigned NOT NULL,
`name` varchar(5) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `products` (`id`, `name`) VALUES
(1, 'Shirt'),
(2, 'Pants'),
(3, 'Socks');
CREATE TABLE IF NOT EXISTS `tags` (
`tag_id` int(6) unsigned NOT NULL,
`product_id` int(6) unsigned NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `tags` (`tag_id`, `product_id`) VALUES
(50, 1),
(51, 1),
(50, 2);
Fiddle: http://sqlfiddle.com/#!9/3f58a16/1小提琴: http://sqlfiddle.com/#!9/3f58a16/1
1 - I need a query that will get all products with ALL tags. 1 - 我需要一个查询来获取所有带有所有标签的产品。 There can be a variable number of tagged filtered by.
可以有可变数量的标签过滤。 (ex: 50 AND 51 AND... )
(例如:50 和 51 和...)
SELECT products.id, products.name
FROM products
JOIN (
SELECT product_id, count(DISTINCT tag_id) AS c
FROM tags
WHERE tags.tag_id IN(50,51)
GROUP BY product_id
) t ON t.product_id = products.id
WHERE t.c = 2
2 - I need a query that will get all products with ANY tags. 2 - 我需要一个查询来获取所有带有任何标签的产品。 There can be a variable number of tagged filtered by.
可以有可变数量的标签过滤。 (ex: 50 OR 51 OR... )
(例如:50 或 51 或...)
SELECT products.id, products.name
FROM products
JOIN (
SELECT product_id, count(DISTINCT tag_id) AS c
FROM tags
WHERE tags.tag_id IN(50,51)
GROUP BY product_id
) t ON t.product_id = products.id
My question is if this is a fine way to go about getting the results I need我的问题是,这是否是 go 关于获得我需要的结果的好方法
products产品
id | name
1 Shirt
2 Shoes
3 Pants
tags标签
product_id | tag_id
1 50
1 51
2 50
Desired result (where tags are 50 AND 51)期望的结果(其中标签为 50 和 51)
id | name
1 Shirt
For Case1
You can try the below -对于
Case1
,您可以尝试以下方法 -
SELECT products.id, products.name
FROM products join tags on products.id=product_id
where tag_id in (50,51)
group by products.id, products.name
having count(distinct tag_id)=2
For Case2
you don't need the group by
with having
clause对于
Case2
,您不需要group by
with having
子句
SELECT distinct products.id, products.name
FROM products join tags on products.id=product_id
where tag_id in (50,51)
You can use the exists
for the first query as follows:您可以将
exists
用于第一个查询,如下所示:
SELECT p.id, p.name
FROM products p join tags t on p.id=t.product_id
where t.tag_id in (50,51)
And exists
(Select 1 from tags tt
Where tt.tag_id in (50,51)
And tt.tag_id <> t.tag_id
And tt.product_id = t.product_id)
For second query just use IN
as mentioned in other answer.对于第二个查询,只需使用其他答案中提到的
IN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.