情景
在自己写sql语句查询的时候,表A 与 表B存在关联字段,A表与B表的关系是一对多,但是A的数据量与B的数据量适情况而定 查询表A数据时需要表b中的一些状态限制。类似sql:
select *
from A
where exists(select 1 from B where A.id = B.apply_id and b.status = ??? )
亦或者
select *
from A
where A.id in (select B.apply_id from B where A.id = B.apply_id and b.status = ??? )
适用情况
因为也是自己实际遇到的问题,查了一下大佬的测试结果在此分享一下。
- exists 适用于B表的数据量大于表A
- in 适用于 A表的数据量大于表B
优化的一种方式
select *
from A
left join
(select B.id ,B.apply_id from B where b.status =??? ) C on C.apply_id = A.id where C.id is not null
ps:不建议适用select *