SQL 求优化一条简单查询语句
SELECT * FROM department
WHERE depid NOT IN (SELECT F_depid FROM F_Department)
根据id查询在department所含而F_Department不含的记录。用上面那条语句感觉效率很低,请教若干更高效,执行时间更短的语句。
------解决方案--------------------select
*
from
department as a
left join F_Department as b on a.depid=b.F_depid
where
a.depid is null
depid,F_depid 建立索引
------解决方案--------------------
SELECT * FROM department as a
WHERE not exists(SELECT * FROM F_Department as b where a.depid = b.F_depid)
------解决方案--------------------非关联子查询一般都不是很高效
------解决方案--------------------
not exists也不会走索引的。一楼的方法可以试试
------解决方案--------------------装个 NOT IN 不仅速度慢,其实还有一个问题,就是如果not int()括号里有null值的时候,会导致逻辑错误,查询出不正确的结果。
所以,建议你想上面提到的一样,可以用left join,或者not exists来实现