问题
I have following tables
Tags
id | tag_name | slug |
1 | tag1 |tag1
2 | tag1 |tag1
products
id | proudct_name
1|product1
2|product2
product_tags
id | product_id | tag_id
1|1||1
2|1|2
3|2|1
i need retrieve only those product which belongs to both tag1 and tag2
select * from `products` INNER JOIN product_tags ON products.id=product_tags.product_id
INNER JOIN tags ON tags.id=product_tags.tag_id WHERE product_tags.tag_id=1 AND product_tags.tag_id=2
But my query return empty result
回答1:
This will look the product that in both tables:
select * from `products` a where exists(select 1 from product_tags b where b.tag_id = 1 and a.product_id = b.product_id) and exists(select 1 from product_tags b where b.tag_id = 2 and a.product_id = b.product_id)
回答2:
You can do what you want with inner join
, which appears to be what you are trying. You just need to inner join
twice:
select p.*
from products p join
product_tags pt1
on pt1.product_id = p.id and pt1.tag_id = 1 join
product_tags pt2
on pt2.product_id = p.id and pt2.tag_id = 2;
This might be easier to code in Laravel.
Your version doesn't work because the tag cannot be both "1" and "2" at the same time -- it can have different rows with those values but only one value per row.
Also, the tags
table is not needed for the query.
来源:https://stackoverflow.com/questions/59691891/myql-pivot-join-fails