sql 主从表查询

来源:百度知道 编辑:UC知道 时间:2024/06/07 21:01:31
A,B表的主从表 B是子表 A表的ID和B表的Parentid关联
如何查询A的ID 在B表中Parentid存在的记录 (A ,B表都是大表 如何速度快)

select A.* from A,B
where A.id = B.parentid

select * from A where exists (select 1 from B where Parentid=A.ID)

使用exists可以提高查询速度,不要用in来查询,in是要全表扫描的!

以上,希望对你有所帮助!

直接采用联结应该是最快的
因为主表与从表都具有索引
SELECT *
FROM A JOIN B ON A.ID = B.ID

ytbelwxg :
我真不明白,你既然知道in比较慢,难道你不知道join比exist扫描更加快?

楼上的,exists跟in都是要扫描的,不过exists返回的是布尔值,in是要去比较数值范围的,所以慢点

select * from A where exists (select 1 from B where Parentid=A.ID) group by A.ID