Sunday, November 24, 2013

How can I join the count in MySQL?

If I have two tables one is:

CAR

| ID |  MAKER |---------------|  1 |  Honda ||  2 | Toyota ||  3 |   Ford ||  4 |  Honda ||  5 |   Ford ||  6 |  Honda |

where id is the car id number & maker is the maker of the car

and the other is

Purchase

| CUSTID | CARID |------------------|      1 |     1 ||      1 |     4 ||      1 |     6 ||      2 |     1 ||      2 |     2 ||      2 |     4 ||      2 |     6 ||      3 |     2 ||      4 |     5 ||      4 |     2 |

where custid is the id of the customer & carid is the id to a specific car

Is there a way to join the two together & then figure out which customers have bought ALL the Hondas?

Try this query:

select P.CustIDfrom purchase Pinner join CAR C on P.CarID=C.CarIDWHERE C.Maker like '%Honda%'group by CustIDhaving count(P.CarID)=    (select count(*) from CAR C where C.Maker like '%Honda%')

SQL FIDDLE

No comments:

Post a Comment