现在有两个表:
Info 表和 InfoToCategory表
INFO表的简单结构如下
InfoId int
Desc text
InfoToCategory表结构如下
InfoId int
Category varchar(20)
infotocategory表是一对多的关系 也就是一个Info需要对应几个Category 例如我表内容如下
info 表
1000000 desc
1000001 desc
infotocategory表内容如下
1000000 category1
1000000 category2
1000000 category3
1000001 category2
我现在想查询结果如下:同时属于类别category1和category2 的info 也就是查询结果为
100000 desc
但是我实现不了这个查询 希望高手帮帮忙 指点下
SELECT * FROM info WHERE InfoId IN (SELECT DISTINCT InfoId FROM infotocategory WHERE Category IN ('category1','category2'))
我没有在SQL中测试,但是应该是没问题,您可以试下,如果数据量很大,您可以优化下,比如后面的select可以取消in,写成两个select然后union all一下
楼上的语句有问题;
SELECT * FROM info
Inner Join infotocategory c1 ON info.InfroId=c1.InfoId
Inner Join infotocategory c2 ON info.InfroId=c2.InfoId
WHERE c1.Category ='category1' AND c2.Category ='category2'
select I1.* from info I1 right join (
select c1.*,c2.* from
(select * from infotocategorywhere Category ='category1') c1
inner join
(select * from infotocategorywhere Category ='category2') c2
on c1.InfoId=c2.InfoId ) I2
on I2.InfoId=I1.InfoId
select * from Info where infoid in (
(select infoid from infotocategory where category='category1')
intersect
(select infoid from infotocategory where category='category2')
) 经过测试啦,应该没有问题