2016-08-09 36 views
0

我有兩個表格:shop_item(父母)和shop_products(孩子)。獲取SQL中兒童的記錄總數

在表shop_products有列shop_item_id,它表明,他的父母是什麼。有些父母有很多孩子。在表shop_products中也有專欄shop_number,這是唯一的。我的目標是找到所有有孩子的父母,例如123(例如)。我可以通過它achive:

SELECT shop_products.shop_number, shop_products.shop_item_id, shop_item.* 
FROM shop_products, 
    shop_item 
WHERE shop_products.shop_number LIKE '123%' 
    AND shop_item.id = shop_products.shop_item_id; 

這一個工作,但我想還可以得到這些孩子的數量(因爲作爲結果,我得到父母的),但我不知道這是否是甚至有可能。

編輯:

實施例表shop_item

+----+-------+-----+ 
| id | name | ... | 
+----+-------+-----+ 
| 1 | test1 | ... | 
| 2 | test2 | ... | 
| 3 | test3 | ... | 
| 4 | test4 | ... | 
+----+-------+-----+ 

實施例表shop_products

+----+--------------+-------------+-----+ 
| id | shop_item_id | shop_number | ... | 
+----+--------------+-------------+-----+ 
| 1 | 1   | 12345  | ... | 
| 2 | 2   | 1234567  | ... | 
| 3 | 1   | 14486  | ... | 
| 4 | 3   | 32333  | ... | 
| 5 | 1   | 12399  | ... | 
| 6 | 4   | 12325  | ... | 
| 7 | 2   | 25511  | ... | 
| 8 | 1   | 42387  | ... | 
+----+--------------+-------------+-----+ 

期待的結果:

+----+----------+-----+ 
| id | children | ... | 
+----+----------+-----+ 
| 1 | 2  | ... | 
| 2 | 1  | ... | 
| 4 | 1  | ... | 
+----+----------+-----+ 
+2

添加一些示例表和預期結果(只是足以描述問題)。 – jarlh

+0

@jarlh見編輯。 – debute

回答

0

首先,學會使用正確的,明確的join語法。簡單的規則:從不FROM子句中使用逗號。 總是使用JOIN

然後,你的問題的答案是GROUP BY。所以,找父母

SELECT s.shop_number, COUNT(*) 
FROM shop_products p JOIN 
    shop_item i 
    ON p.shop_number LIKE '123%' AND 
     i.id = p.shop_item_id 
GROUP BY s.shop_number; 

如果你想與列的原始詳細數據。接着,添加使用相關子查詢:

SELECT s.shop_number, si.*, 
     (SELECT COUNT(*) FROM shop_item si2 WHERE si2.id = p.shop_item_id) as cnt 
FROM shop_products p JOIN 
    shop_item i 
    ON p.shop_number LIKE '123%' AND 
     i.id = p.shop_item_id; 
0

你可以試試這個,如果你需要得到唯一的共同項目(即僅擁有父母的孩子,有孩子家長):

select shop_products.shop_number, shop_products.shop_item_id, 
     shop_item.*, Count(shop_products.shop_item_id) over (partition by shop_products.shop_item_id) as ChildrenCount 
from shop_item 
inner join shop_products 
on shop_products.shop_item_id = shop_item.shop_item_id 
where shop_products.shop_number LIKE '123%' 

否則,如果你想獲得數據,而不管共同使用左外連接:

select shop_products.shop_number, shop_products.shop_item_id, 
    shop_item.*, Count(shop_products.shop_item_id) over (partition by shop_products.shop_item_id) as ChildrenCount 
from shop_item 
left outer join shop_products 
on shop_products.shop_item_id = shop_item.shop_item_id 
where shop_products.shop_number LIKE '123%'