mysql子表查询 (EXISTS)

问题

1、假设主表为A,子表为B(他们以A表的唯一id关联)
A表
account_idnamegenderage
1小明22
2小红22
3小军25
B表
book_idaccount_idbook_nameprice
a1西游记55
b1红楼梦55
c1哈利波特40
d2小王子25
e3暴风雨23
2、当我们想要查询两个表的记录的时候,通常都会想到 left join。例:(select * from A left join B where A.account_id = B.account_id)
3、按分页来思考,我们只想要A表的记录,但是需要B表的一些字段作为搜索条件。如果查找到A表只有1条记录,B表有2条符合的记录,这样就会产生两条记录。例:(select * from A left join B where A.account_id = B.account_id where B.price = 55)
account_idnamegenderagebook_idaccount_idbook_nameprice
1小明22a1西游记55
1小明22b1红楼梦55
解决(EXISTS)
select * from A where 1 and exists( select 1 from B where B.account_id = A.account_id and B.price = 55 )
account_idnamegenderage
1小明22
好处:A表搜索到多少条数据就返回多少条,可以方便分页,又可以拿B表作为条件来搜索,同样也可以拿C表一起搜索。exists()只返回true和false。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值