I have two tables such as Car
and Driver
. Car
table has two columns. which are car_id
and car_name
. Driver
table also has two columns. which are driver_id
and car_type
.
Cars
car_id | car_name |
---|---|
1 | Audi |
2 | BMW |
3 | Ferrari |
Drivers
driver_id | car_type |
---|---|
1 | BMW |
1 | Audi |
1 | Ferrari |
2 | Audi |
2 | Cheverolet |
2 | Tata |
3 | Ferrari |
How do I find which driver is driving more than two cars?
CodePudding user response:
By using the Having clause
SELECT Driver_id
FROM Driver
GROUP BY Driver_id
HAVING COUNT(*) > 1
CodePudding user response:
SELECT Driver_id
FROM YourTable
Where COUNT(Driver_id) > 1
CodePudding user response:
Your tables have surrogate primary keys but the Driver
table uses the car name, not id, to relate cars to drivers.
So you can find the drivers with more than one car without needing to join to the car table (unless you need the car_id
value)
The query needs to count the distinct type of car grouped by driver_id
, having a count of car type greater than one.
From the information in that sentence you should be able to look up how to write it in SQL ;)
If the Driver
table has a unique constraint on the two fields driver_id
/car_type
then you can use the query Dijkgraaf posted and not worry about the type of car they drive.
From the data you have shown there can't be any referential constraint (foreign key) of the cars drivers drive because you have
Cheverolet
(sic), Tata
, and Ferrari
in the Driver
table but those cars are not in the Car
table.