Posted: 26 October 2006 at 3:50pm | IP Logged
|
|
|
WARNING - FOR SQL GEEKS ONLY!
I managed to reqrite a SQL query I wrote earlier this week such that it now takes less than a second to run, rather than a minute and a half! Geeky I know... but I was well chuffed! 
Original query: SELECT DISTINCT tblServerHotfixes.name, tblServerHotfixes.hotfix_name FROM ((tblServerHotfixes INNER JOIN tblServers ON tblServerHotfixes.name=tblServers.name) INNER JOIN relnHotfixToGroup ON tblServers.hotfix_group_id=relnHotfixToGroup.hotfix_group_id) INNER JOIN tblHotfix ON relnHotfixToGroup.hotfix_id=tblHotfix.id WHERE (((Exists (select * from qryListReqdHotfixes WHERE tblServerHotfixes.name = qryListReqdHotfixes.name AND tblServerHotfixes.hotfix_name = qryListReqdHotfixes.hotfix_name))=False)) ORDER BY tblServerHotfixes.name, tblServerHotfixes.hotfix_name;
Is now: SELECT H1.name, H1.hotfix_name AS extra_hotfix FROM tblServerHotfixes AS H1 WHERE H1.name IN (SELECT name FROM tblServers WHERE tblServers.hotfix_group_id > 0) AND H1.hotfix_name NOT IN ( SELECT tblHotfix.hotfix_name FROM tblServers, relnHotfixToGroup, tblHotfix WHERE tblServers.name = H1.name AND tblServers.hotfix_group_id=relnHotfixToGroup.hotfix_group_id AND relnHotfixToGroup.hotfix_id=tblHotfix.id) ORDER BY H1.name, H1.hotfix_name;
I think this proves that joining tables using SELECT is FAR FAR FAR better than joining them with INNER JOINs... (also - never use SELECT DISTINCT if you can help it... if you have to use DISTINCT, you're probably SELECTing the wrong data anyway!) 
Another tip - using EXISTS is better than "IN" if youre doing positive searches as EXISTS will exit the search when it finds the 1st object, but "IN" will be forced to search the entire table...
Edited by Demonboy on 26 October 2006 at 3:51pm
__________________ There is no IRL, there's just AFK.
|