patternsqlMinor
Improve query: find users who are neither friends nor fans of a user
Viewed 0 times
arewhoqueryuserimprovefansnorfindusersfriends
Problem
Please take a look at this query and try to give me any other ideas that will give the exact same results more efficiently.
Here's a live demo.
SELECT username
FROM users
WHERE username NOT IN (
SELECT DISTINCT username
FROM users, friends
WHERE 'user1' IN (you,friend,username)
AND you IN ('user1',username)
AND friend IN ('user1',username))
AND username <> 'user1'Here's a live demo.
Solution
This query will give you the same results
and the SQLFiddle
If you look at the execution plan, it looks like my query grabbed 1 less row throughout the execution and it didn't have to use a temporary or a join buffer.
This Query is more readable than yours, assuming this is what you are trying to do.
SELECT username FROM users
WHERE username NOT IN (SELECT you FROM friends WHERE friend = 'user1')
AND username NOT IN (SELECT friend FROM friends WHERE you = 'user1')
AND username <> 'user1'and the SQLFiddle
If you look at the execution plan, it looks like my query grabbed 1 less row throughout the execution and it didn't have to use a temporary or a join buffer.
This Query is more readable than yours, assuming this is what you are trying to do.
Code Snippets
SELECT username FROM users
WHERE username NOT IN (SELECT you FROM friends WHERE friend = 'user1')
AND username NOT IN (SELECT friend FROM friends WHERE you = 'user1')
AND username <> 'user1'Context
StackExchange Code Review Q#33080, answer score: 7
Revisions (0)
No revisions yet.