现有两张表1试题:choice,中间表2: paperchoice   两表是多对多的关系  choice中有choiceId title 字段,choiceId是主键 
                                                      paperchoice中有paperId choiceId字段为联合主键
现在要查询所有不在中间表中的试题 就是只要中间表有的 就不显示 唉表达的不清楚 用例子说明吧
 choice:  choiceId  title        paperchoice:  paperId choiceId
             1        111                          7      1 
             2        222                          7      2
             3        333                          8      1 
             4        5555                         8      3  
             5        888                          8      4
             6         9999
       需要的结果是   :   choice: choiceId  title
                                     5          888
                                     6           9999 
          就这样子了 SQL语句也行 HQL语句也行 都有是最好 多学习点~~呵呵

解决方案 »

  1.   

    select * from choice c where not exists(select 1 from paperchoice p where p.choiceId = c.choiceId)
      

  2.   

    那就用not in吧select choiceId, title
    from choice 
    where choiceId not in (select distinct(choiceId) from paperchoice)
      

  3.   

     唉,表达错了 刚想编辑的 突然发现我想要的是 当paperId=7的时候 结果为:
    3 333
    4 5555  
    5 888
    6  9999  不知道这条语句怎么实现啊?
      

  4.   

    select * from choice c where not exists(select 1 from paperchoice p where p.choiceId = c.choiceId)
      

  5.   

       唉,表达错了 刚想编辑的 突然发现我想要的是 当paperId=7的时候 结果为:
    3 333
    4 5555   
    5 888
    6 9999 这条语句可以实现吗?
      

  6.   

    稍微改一下就可以了
    select choiceId, title
    from choice  
    where choiceId not in (select distinct(choiceId) from paperchoice where paperId = 7)
      

  7.   

    select * from choice c where not exists(select 1 from paperchoice p where p.choiceId = c.choiceId and paperId = 7)建议,能不用in 或 not in就不用,用exists或not exists来代替,in的性能太差!
      

  8.   


    不解释,第二次赞成他的观点了,楼主请采纳,能不用not in就不要用。