[英]How do I write a query related to count
I have two tables such as Car
and Driver
.我有两张表,例如
Car
和Driver
。 Car
table has two columns. Car
表有两列。 which are car_id
and car_name
.它们是
car_id
和car_name
。 Driver
table also has two columns. Driver
表也有两列。 which are driver_id
and car_type
.它们是
driver_id
和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?如何找到驾驶超过两辆车的司机?
By using the Having clause通过使用 Have 子句
SELECT Driver_id
FROM Driver
GROUP BY Driver_id
HAVING COUNT(*) > 1
Your tables have surrogate primary keys but the Driver
table uses the car name, not id, to relate cars to drivers.您的表具有代理主键,但
Driver
表使用汽车名称而不是 id 将汽车与司机联系起来。
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)所以你可以找到拥有不止一辆车的司机,而不需要加入 car 表(除非你需要
car_id
值)
The query needs to count the distinct type of car grouped by driver_id
, having a count of car type greater than one.查询需要计算由
driver_id
分组的不同类型的汽车,汽车类型的计数大于一。
From the information in that sentence you should be able to look up how to write it in SQL ;)从该句子中的信息中,您应该能够查找如何用 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.如果
Driver
表对两个字段driver_id
/ car_type
具有唯一约束,那么您可以使用 Dijkgraaf 发布的查询,而不必担心他们驾驶的汽车类型。
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.根据您显示的数据,驾驶员驾驶的汽车不能有任何参考约束(外键),因为您在
Driver
表中有Cheverolet
(sic)、 Tata
和Ferrari
但这些汽车不在Car
表中。
SELECT Driver_id
FROM YourTable
Where COUNT(Driver_id) > 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.