所以我对SQL很新,并且在我目前的实习期间负责改进/记录程序。
为了切入追逐,我在桌面上运行以下查询:
SELECT COUNT(*) as NumofAccounts
FROM Accounts
WHERE Deleted = 0
AND Account_ID In ( SELECT DISTINCT Account_ID FROM Tasks WHERE Deleted = 0 );
产生NumofAccounts = 18的结果。
但原始查询是:
SELECT COUNT(*) as NumofAccounts
FROM Accounts
WHERE Deleted = 0
AND Account_ID In ( SELECT Account_ID FROM Tasks WHERE Deleted = 0 );
这两个查询都会产生NumofAccounts = 18,但是,如果一个查询隔离了这部分查询:
SELECT Account_ID FROM Tasks WHERE Deleted = 0;
有736行结果,其中许多是重复的Account_ID。
但如果加上DISTINCT:
SELECT DISTINCT Account_ID FROM Tasks WHERE Deleted = 0;
只有18行结果,与NumofAccounts相吻合。
有没有办法分析这两个查询之间的运行时或效率差异?
对不起啰嗦的帖子感到抱歉!
答案 0 :(得分:3)
答案 1 :(得分:0)
你可以使用存在可以做得更好的存在..
SELECT COUNT(*) as NumofAccounts
FROM Accounts a
WHERE Deleted = 0
AND exists ( SELECT Account_ID FROM Tasks t WHERE t.Deleted = 0 and t.account_id=a.account_id) ;
当你说效率时,你需要缩小到像
这样的领域1.执行时间需要改进 2.查询消耗更多的CPU 3.使用更多内存
如果您的效率与执行时间相关,则上述查询可以更好地工作..
您的两个查询可能会根据多个因素(例如,这些表上可用的索引,执行计划选择
)而有所不同