表1 产品表 product(id,title)
表2 分类表 category(id,title) 这个问题中可以不要用到该表
表2 关系表 product_category(pid,cid)
其它关系表是多对多的,既一个分类有多个产品,一个产品可以属于多个分类
现在要求分类ID包含 3,4,6 的产品(既某产品一定要有这3个分类)的SQL。。谢谢大家。。
表2 分类表 category(id,title) 这个问题中可以不要用到该表
表2 关系表 product_category(pid,cid)
其它关系表是多对多的,既一个分类有多个产品,一个产品可以属于多个分类
现在要求分类ID包含 3,4,6 的产品(既某产品一定要有这3个分类)的SQL。。谢谢大家。。
From product_category a,product_category b,product_category c
Where a.pid=b.pid and b.pid=c.pid
and a.cid=3 And b.cid=4 And c.cid=6
from product_category
where cid IN (3,4,6)
Group by pid
Having count(*)=3
create table newtb select * from oldtb
SELECT * FROM `product` as p WHERE
exists (select 1 from product_category where pid=p.id and cid=3)
and exists (select 1 from product_category where pid=p.id and cid=4)
and exists (select 1 from product_category where pid=p.id and cid=6)
and exists 虽然看上去这样的SQL很长,但我觉得product_category中的cid做了索引,且此SQL中的where是and和exists 这二个关键字执行效率都是很高的,不知道大家意下如何。
如果大家觉得还有好的方法,请告之,非常谢谢