我的数据库设计有3个表格如下:
products
pid pname pprice
tags
tag_id tag_name
products_tag ==> Unique(pid,tag_id)
pid tag_id
65 1
65 3
66 2
88 2
88 4
88 3
我要求获得tagid = 2和3和4的所有pid。因此,这种情况下的结果是88(pid)。这个问题陈述的SQL查询是什么?
答案 0 :(得分:1)
select pid
from products_tag
where tagid in (2,3,4)
group by pid
having count(tagid) = 3
答案 1 :(得分:0)
使用条件COUNT
SELECT PID, COUNT(CASE WHEN tag_id IN (2,3,4) THEN 1 END) as total
FROM products_tag
GROUP BY PID
HAVING COUNT(CASE WHEN tag_id IN (2,3,4) THEN 1 END) = 3