2015-10-05 164 views
0

如何使用查詢分別查看a,b,c,d添加的產品數量?選擇加入SQL查詢計數

table1的

admin_id admin_name 
3   a 
4   b 
5   c 
6   d 

表2

admin_id products 
3   pDeal 
3   pSeal  
4   pAeal 
5   pZeal 
6   pXeal  
3   pHeal 
6   pPeal 

回答

3

你需要一個簡單的聯接和統計查詢:

SELECT table1.admin_name, COUNT(*) as cnt 
FROM 
    table1 INNER JOIN table2 
    ON table1.admin_id = table2.admin_id 
GROUP BY 
    table1.admin_name 
+0

而不是INNER JOIN, LEFT JOIN在這裏最適合,不是嗎?由於admin_name不會被編入索引(在大多數情況下),因此列admin_name上的GROUPING可能會導致查詢緩慢! – MaK

+0

@MaK你可以通過'COUNT(*)'使用'INNER JOIN'或'COUNT(table2.admin_id)'使用'LEFT JOIN',左連接將返回所有管理員,即使是那些有0個產品的管理員,內連接只有那些至少有1個產品 – fthiella

+0

謝謝fthiella – user4464505

0
SELECT t1.admin_name, COUNT(t2.products) 
FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.admin_id = t2.admin_id 
WHERE 1 
GROUP BY t2.admin_id 

的LEFT JOIN將確保情況下,當表2沒有按對於某些管理員沒有任何記錄表1.

+0

@ shA.t我不認爲它會。看看這個小提琴:http://sqlfiddle.com/#!9/9c086/2 – MaK

1

嘗試......

SELECT a.admin_name, COUNT(b.products) as 'CountOfProducts' 
    FROM table1 a INNER JOIN table2 b ON a.admin_id = b.admin_id 
    GROUP BY a.admin_name 
1

這樣使用這個

SELECT adm.admin_name,COUNT(pdr.products) as ProductCnt 
FROM table1 AS adm 
JOIN table2 AS pdr 
    ON adm.admin_id = pdr.admin_id 
GROUP BY adm.admin_id; 
0

您可以使用內選擇:

SELECT 
    table1.admin_name, 
    (SELECT COUNT(*) 
    FROM table2 
    WHERE table1.admin_id = table2.admin_id) As cnt 
FROM 
    table1;