2017-08-26 48 views
0

我想要做的是返回卡車所有者的總數超過指定的限制 所有記錄在下面的情況下,假設總限制是3我想獲取所有誰擁有3噸或更多的卡車註冊Sql語句groupby限制條件

所以查詢,如果限制爲3只返回地鐵轉,因爲他們有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 

我如何添加t他限制我的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" 

如何添加限制

回答

4

使用具有聲明:

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