表1
列id,自增整数,主键
列book_id,书的ID
列book_name,书的名称
列is_exist,是否有货,1有,0没有表2
列id,自增整数,主键
列book_id,书的ID
列level,书的级别,读者打分用(1星到5星)
列user,读者查询1:
请检索出tom没有读过、而其他人读过的、有货的书
检索出以下几列:书ID,书名,检索2:
检索出至少有三个读者打过分的书,且这些书的打分相同,且书有货
检索出以下几列:书ID,书名,书的级别

解决方案 »

  1.   

     查询1: 
     请检索出tom没有读过、而其他人读过的、有货的书 
     检索出以下几列:书ID,书名, 
     
     select book_id,book_name
     from 表1
     where is_exist=1
     and exists (select 1 from 表2 where book_id=表1.book_id)
     and not exists (select 1 from 表2 where book_id=表1.book_id and user='tom')
     
      
     检索2: 
     检索出至少有三个读者打过分的书,且这些书的打分相同,且书有货 
     检索出以下几列:书ID,书名,书的级别
     
     select 表1.book_id,表1.book_name,b.level
     from 表1,(select book_id,level from 表2 group by book_id,level having count(*)>=3) b
     where 表1.book_id=b.book_id
      

  2.   

    谢谢ACMAIN_CHM大侠,高手啊,这两句都非常好用
    能再问一下么, 怎么限制上面的查询只返回第一条结果啊
    拜谢中
      

  3.   

    sql语句后加个   limit 1
      

  4.   

     select book_id,book_name
     from 表1
     where is_exist=1
     and exists (select 1 from 表2 where book_id=表1.book_id)
     and not exists (select 1 from 表2 where book_id=表1.book_id and user='tom')
    LIMIT 1 select 表1.book_id,表1.book_name,b.level
     from 表1,(select book_id,level from 表2 group by book_id,level having count(*)>=3) b
     where 表1.book_id=b.book_id
    LIMIT 1