PDA

View Full Version : Getting non distinct rows based on enum value


rookiecoder
10-04-2009, 07:22 PM
Hi,
I have a table TEST with 3 fields ; id (Primary) , worker_id(int) , type( enum where possible values are 'a','b','c')

Now, I am trying to retrieve all rows where I have the same worker_id and type set to 'a'.

e.g
Test

id | worker_id | type
1 | 1 | a
2 | 1 | b
3 | 2 | c
4 | 1 | a

So I would want rows 1 and 4 to be returned, but can't figure the sql query which can get it for me

Old Pedant
10-04-2009, 09:41 PM
SELECT t1.*, t2.id AS secondID
FROM test AS T1, test AS t2
WHERE T1.worker_id = T2.worker_id
AND T1.type = T2.type
AND T1.id < T2.id

If you omit that last condition (T1.id < T2.id) the query will still work, but you will get each pair of matches *twice*.

That is, you would get:

1 | 1 | a | 4
4 | 1 | a | 1

That last AND condtion ensures each matched pair shows only once.