我们要做的是返回所有卡车车主总数超过指定限额的记录 在下面的情况下假设总限制是3我想取得所有拥有3辆或更多卡车的车主
所以如果限制为3的查询应该只返回metro trans,因为他们有3辆或更多卡车
这是我的数据库结构
tbl_trucks
id owner_id .....
1 12
2 12
3 13
4 12
tbl_truck_owners
id owner
12 metro trans
13 mush elec
如何将限制添加到我的sql语句
这就是我试过的
SELECT
COUNT(tbl_trucks.owner_id), tbl_truck_owners.owner
FROM tbl_trucks
LEFT JOIN tbl_truck_owners ON tbl_trucks.owner_id = tbl_truck_owners.id
WHERE //stuck at adding the limit
GROUP BY owner_id"
如何添加限制
答案 0 :(得分:4)
使用HAVING语句:
SELECT COUNT(tbl_trucks.owner_id), tbl_truck_owners.owner
FROM tbl_trucks
LEFT JOIN tbl_truck_owners ON tbl_trucks.owner_id = tbl_truck_owners.id
GROUP BY owner_id
HAVING COUNT(tbl_trucks.owner_id) >= 3