views:

936

answers:

4

I want to select only rows that are unique according to the column userid from a mysql table. So if I have two rows with the same userid none of them gets selected but if its only one it gets selected.

I use the following code:

SELECT T.id,T.name,T.userid FROM tbltest T WHERE userid NOT IN (SELECT userid FROM tbltest WHERE tbltest.id<>T.id);

Is this the fastest way to do it?

Thanks!

+6  A: 

How is this

SELECT T.id,T.name,T.userid 
FROM tbltest T 
GROUP BY T.userid
HAVING COUNT(T.userid) = 1;
zodeus
Errr surely you don't need the NOT IN?
Greg
Probably not, but all I did was add the GROUP BY and HAVING to the statement he posted.
zodeus
I don't think this will work. Not a MySQL user, but doesn't GROUP BY have to list all columns that aren't aggregated? Most RDBMSs do...
Ken White
+1  A: 

Try

SELECT T.id, T.name, T.userid, count(*) AS count FROM tbltest GROUP BY T.userid HAVING count = 1;

Chris J
A: 

I don't think that's the fastest way... you could try:

SELECT T.id, T.name, T.userid, COUNT(*) AS num 
FROM tbltest T GROUP BY T.userid HAVING num = 1

Or

SELECT T.id, T.name, T.userid, COUNT(*) AS num FROM tbltest T
WHERE NOT EXISTS
(SELECT 1 FROM tbltest T2 WHERE T2.userid = T.userid AND T2.id != T.id)
Greg
A: 

Distinct

Andrew G. Johnson