我有一个MySQL问题。
我有两张桌子:公司&产品
现在我需要在Company表中选择行并计算每个公司的产品数量。
以下是一个例子:
Company:
---------------
| id | Name |
---------------
| 1 | c1 |
| 2 | c2 |
| 3 | c3 |
| 4 | c4 |
---------------
Products:
--------------------
| id | companyid |
--------------------
| 1 | 3 |
| 2 | 1 |
| 3 | 4 |
| 4 | 3 |
| 5 | 2 |
--------------------
我需要得到的结果是:
----------------------------
| id | Name | numproducts|
----------------------------
| 1 | c1 | 1 |
| 2 | c2 | 1 |
| 3 | c3 | 2 |
| 4 | c4 | 1 |
----------------------------
很抱歉,如果问题是基本的。 提前谢谢。
答案 0 :(得分:1)
你可以使用分组和计数来得到你的答案
select
c.id, c.name, count(*) as numproducts
from
company c join products p on c.id = p.companyid
group by
c.id, c.name
答案 1 :(得分:1)
加入2个表,然后按公司表中所需的字段进行分组:
SELECT
c.name
, COUNT(p.id) AS no_of_products
FROM company c
INNER JOIN products p
ON c.id = p.companyid
GROUP BY
c.name
答案 2 :(得分:0)
您可以使用此查询
SELECT * ,
(SELECT COUNT( 1 )
FROM products p2 WHERE p2.companyid = p1.id) AS no_of_records
FROM `company` p1