tags:

views:

71

answers:

5

I have a list of usernames (with a column called "username") + other info in my "users" table.

I also have another list of usernames (with a column called "username") in my smaller "recentusers" table.

How can I create a mysql query to get all the usernames that are in the "users" table but not in the "recentusers" table?

I know it is probably very simple, but any help would be appreciated!

+4  A: 
select username from users where username not in (select username from recentusers)

Then after the first username add in the other information you want to select as well.

As pointed out by OMG Ponies, this query will run as fast as using Left Join or Is null.

Corey Sunwold
FYI: This will run as fast as a query using LEFT JOIN/IS NULL: http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/
OMG Ponies
@OMG Ponies: Excellent information. I did not know that. Thanks for pointing that out.
Corey Sunwold
@OMG Ponies: thanks for the link. what a great nickname!
chris
+1  A: 

The NOT IN keyword should be helpful :

SELECT username
FROM users
WHERE username NOT IN (
    SELECT username
    FROM recentusers
)
Wookai
A: 

Joins should be faster than subqueries, though I do not really know if mysql supports this.

select * from users
left outer join recentusers
on users.key = recentusers.key
BeowulfOF
That's incorrect regarding MySQL, and your query doesn't list users that are **not** in the `recentusers` table: http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/
OMG Ponies
The query is right, concerning standard SQL syntax, look out for the outer keyword. Secondly I wrote that I do not know if MySql supports this syntax, since MySql cooks its own meal.
BeowulfOF
`@BeowulfOF`: the query is wrong, since you forgot to add `recentusers.key IS NULL`
Quassnoi
+1  A: 
SELECT * FROM users
    LEFT JOIN recentusers USING (username) 
    WHERE recentusers.username IS NULL;
jcdyer
+1  A: 

You can also use a left join (which will perform faster than a subquery):

SELECT
    users.username
FROM
    users LEFT JOIN recentusers
        ON users.username = recentusers.username
WHERE
    recenterusers.username is null
jonstjohn