获取SQL中的子项记录总数

时间:2016-08-09 10:35:46

标签: mysql sql

我有两个表:shop_item(父母)和shop_products(孩子)。

在表shop_products中,有一列shop_item_id,表示他的父母是什么。有些父母有很多孩子。在表shop_products中,还有列shop_number,这是唯一的。我的目标是找到所有父母都有孩子,以123开头(例如)。我可以通过以下方式实现:

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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%'