具体是这样的,有post表关联好cat表每个post可能对应多个cat。
现在我要筛选出属于cat A并属于cat B的post记录
用post jion 了cat表,该如何写后面的where????
谢谢各位了,sql语句基本不太会
其实目的就是给wordpress这个博客程序增加多目录筛选的功能
现在我要筛选出属于cat A并属于cat B的post记录
用post jion 了cat表,该如何写后面的where????
谢谢各位了,sql语句基本不太会
其实目的就是给wordpress这个博客程序增加多目录筛选的功能
from post a ,cat b , cat c
where a.id=b.postid and a.id=c.postid and b.name='A' and c.name='B'
inner join cat c on a.id=c.postid
where b.name='A' and c.name='B'
post表
postid title content
1 XX XX
2 XX XX
3 XX XXcat表
catid catname
1 A
2 B
3 C
post_cat表
post_cat_id postid catid
1 1 1
2 1 2
3 2 3
4 3 1现在要找出所有既属于catname A又属于catname B的post也就是最后应该找了postid为1那条记录
from post_cat a1,post_cat a2,cat c1,cat c2
where a1.catid=c1.catid and a2.catid=c2.catid
and a1.postid=a2.postid
and c1.catname='A' and c2.catname='B'
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。
from ((post_cat a1 inner join post_cat a2 on a1.postid=a2.postid)
inner join cat c1 on a1.catid=c1.catid)
inner join cat c2 on a2.catid=c2.catid where c1.catname='A' and c2.catname='B'
感谢ACMAIN_CHM 和 wwwwb。两种方式都测试通过可以使用。由于容易修改,我最后使用了WWWWA的inner join的方式。
SELECT postid from post_cat
group by postid
having sum(iif(catid=1,1,0))+sum(iif(catid=2,1,0))=2orSELECT a.postid from post_cat a inner join cat b
on a.catid=b.catid
group by a.postid
having sum(iif(b.catname='A',1,0))+sum(iif(B.catname='B',1,0))=2