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。