0

I have a table with firms that rent cars, with columns like

Firms | Car 
GD1   | CAR1 
GD1   | CAR2 
GD2   | CAR3 
GD3   | CAR4 

And also other one with the cars rented by the clients, like this:

Client | Car Rented
C1     | CAR1
C1     | CAR2
C1     | CAR3
C1     | CAR4
C2     | CAR4
C3     | CAR1
C3     | CAR2
C4     | CAR1
C5     | CAR2

I need to know all the clients that rent all the cars from an specific firm. The only input that I have is the firm name (for instance GD1) If I use GD1 the output should be this one:

Client
C1
C3

It may seem easy, but I'm really having trouble with this one...

Thanks for the time

0

2 Answers 2

1

To know whether a client rents all the car from a particular firm, you need to know how many cars owned by the firm and how many cars rented from the firm by the client. To know how many cars owned by the firm, you can get that by this query:

SELECT      Firms, COUNT(*) AS NUM_OF_CAR
FROM        FirmTable
GROUP BY    Firms

And to know how many cars rented from the firm by the client, you can get by this query:

SELECT      Client, Firms, COUNT(*) AS NUM_OF_CAR
FROM        FirmTable a
INNER JOIN  ClientTable b ON a.Car = b.Car
GROUP BY    Client, Firms

And now you need to get the client that rents all the car, meaning that the NUM_OF_CAR from the first query and the second query must match for the respective firm. Combining both queries above, you can use:

SELECT      DISTINCT Client
FROM        (
            SELECT      Firms, COUNT(*) AS NUM_OF_CAR
            FROM        FirmTable
            GROUP BY    Firms
            ) t
INNER JOIN  (
            SELECT      Client, Firms, COUNT(*) AS NUM_OF_CAR
            FROM        FirmTable a
            INNER JOIN  ClientTable b ON a.Car = b.Car
            GROUP BY    Client, Firms
            ) u
ON          t.Firms = u.Firms AND t.NUM_OF_CAR = u.NUM_OF_CAR
WHERE       t.Firms = 'GD1'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just what I need, also thanks for the two steps explanation that you edited later. Regards
0

I'm also new at mysql but you can try this.

SELECT DISTINCT Client from ClientTable where CarRented=(SELECT Car from FirmTable where Firms='GD1');

1 Comment

Thanks, but have in mind that in this case the subquery will have more than 1 row, so your solution wouldn´t work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.