Myql pivot join fails

旧街凉风 提交于 2020-01-26 03:57:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!