MySQL数据透视连接失败 [英] Mysql pivot join fails

查看:90
本文介绍了MySQL数据透视连接失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表

标签

id | tag_name | slug |
1 | tag1 |tag1
2 | tag1 |tag1

产品

id | proudct_name
1|product1
2|product2

product_tags

id | product_id | tag_id 

1|1||1
2|1|2
3|2|1

我只需要检索属于tag1和tag2的那些产品

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

推荐答案

这将查找两个表中的产品:

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)

这篇关于MySQL数据透视连接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆