求高手指点两个sql查询的写法

jjstar 2011-03-18 09:42:33

表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,书名,书的级别
...全文
56 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2011-03-18
  • 打赏
  • 举报
回复
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
Meteor_Code 2011-03-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jjstar 的回复:]
谢谢ACMAIN_CHM大侠,高手啊,这两句都非常好用
能再问一下么, 怎么限制上面的查询只返回第一条结果啊
拜谢中
[/Quote]
sql语句后加个 limit 1
jjstar 2011-03-18
  • 打赏
  • 举报
回复
谢谢ACMAIN_CHM大侠,高手啊,这两句都非常好用
能再问一下么, 怎么限制上面的查询只返回第一条结果啊
拜谢中
ACMAIN_CHM 2011-03-18
  • 打赏
  • 举报
回复
查询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

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧