具体是这样的,有post表关联好cat表每个post可能对应多个cat。
现在我要筛选出属于cat A并属于cat B的post记录
用post jion 了cat表,该如何写后面的where????
谢谢各位了,sql语句基本不太会
其实目的就是给wordpress这个博客程序增加多目录筛选的功能

解决方案 »

  1.   

    post jion cat on post.id=cat.postid and cat.code in ('A','B')
      

  2.   

    select *
    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'
      

  3.   

    贴一下记录及要求结果出来看看select * from post a inner join cat b on a.id=b.postid 
    inner join cat c on a.id=c.postid 
    where  b.name='A' and c.name='B'
      

  4.   

    感谢楼上三位。怪我没有描述清楚,其实cat 是一个表,只是里面可以存很多cat记录并有一个name字段。也就是post关联两条cat记录,并且要求name为A以及B
      

  5.   

    2#的语句就是把 cat 当成一个表啊。你测试了吗?
      

  6.   

    帖子竟然没有发出,郁闷明明记得我发出了再敲一遍,谢谢wwwwb。目前在上班。晚上回去吧记录发出。
      

  7.   

    不等到回去了,我模拟几个数据。。如下
    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那条记录
      

  8.   

    怎么又多出来个 post_cat表 ?这个在你原来的描述中没有啊。select postid
    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'
      

  9.   

     (不要高估你的汉语表达能力或者我的汉语理解能力)
       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式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)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。   
      

  10.   

    SELECT a1.postid 
    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'
      

  11.   

    问题已经解决谢谢楼上几位的帮助。
    感谢ACMAIN_CHM 和 wwwwb。两种方式都测试通过可以使用。由于容易修改,我最后使用了WWWWA的inner join的方式。
      

  12.   

    还有一种方法
    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