tags:

views:

589

answers:

3

Hi I have a table with one record per person and per item of clothing

so

peter, jumper,blue
peter,trousers,green
sue,dress,green
peter,jumper,red
gordon,jumper,green

I want to write a query to select all people with green jumpers but only if they have no other color jumper

So in the above case it would ONLY select Gordon not greedy old Peter

is that possible?

+3  A: 

This should work, but it's untested. The syntax might also be a little off as I still have Firebird SQL in my head, but you should get the general idea:

SELECT *
FROM myTable AS t1
WHERE t1.clothing = 'jumper' AND t1.color = 'green' 
AND NOT EXISTS(SELECT *
               FROM myTable AS t2
               WHERE t2.person = t1.person AND t2.clothing = 'jumper'
               AND t2.color <> 'green')
lc
This looks good but seems to have killed my mysql server
zzapper
Yep this did it. I had a lot of records to query. To get the execution time down I had to make sure that the main select was as tight as possible so that the sub-select had less to do
zzapper
+1  A: 

I have to run off to a meeting, but a CASE statement might help you out here.

MySQL CASE statement

ericdrum
Like to see a "case" solution to this problem
zzapper
+1  A: 
SELECT *
FROM MyTable t1
WHERE Color = 'green'
AND NOT EXISTS (
    SELECT 1 
    FROM MyTable
    WHERE Color <> 'green'
    AND PersonName = t1.PersonName
)