Search code examples
mysqlsqlcorrelated-subquerysubquery

Comparing Rows Returned by a Query


I have the following tables :

Employee (empid,name,age)
Booking (bookingid,empid,cid)
Cars (cid,name,type).
The contents are in this way:

Employee :

  1. emp1 , A , 32
  2. emp2 , B , 36
  3. emp3 , C , 25
  4. emp4 , D , 40
  5. emp5 , E , 45

Booking:

  1. 1 , emp1, car1
  2. 2 , emp1 , car3
  3. 3 , emp1 , car2
  4. 4 , emp2 , car2
  5. 5 , emp3 , car3
  6. 6 , emp4 , car1
  7. 7 , emp4 , car2
  8. 8 , emp5 , car3
  9. 9 , emp5 , car2
  10. 10 , emp5 , car1

Cars:

  1. car1 , one, Red
  2. car2 , two, Blue
  3. car3 , three, Red

Here's my question : what is the query to return all employee names who have booked a car which isnt red?

Edited :
I should've been more specific with my question the first time.
This link How can I join two tables but only return rows that don't match?
It is about comparing same fields from different tables.The post clearly indicates that the user needs to compare rows from two tables and return ones that don't match.
But that is not my case.As my title suggests,I'd like to know if the rows returned by performing a query can be compared.
I want to get the names of employees who have not booked at least one red car. Considering the values in the tables,
Employee 1 and 5 have booked all cars.
Employee 3 has booked only a red car and
Employee 4 has booked one red and one green car.
Employee 2 has booked a Green car.
Now, what can be the query to return only name of employee 2 is what my question is.(I'm know i can do it by just specifying type='Green' in the where clause but that fails when there are more than two colors.)


Solution

  • select DISTINCT e.Name from #Employee e
    inner join #Booking b on e.EmpID = b.EmpID
    where e.EmpID not in (
        select b.EmpID from #Booking b
        inner join #Cars c on b.CID = c.CID
        where [type] = 'red'
    )