我对SQL很新,不知道我的查询有什么问题。 PLZ指南
我有2个表产品和product_consumer 1到m关系。 我想获得每种产品的所有产品和消费者数量。
这就是我想要的:
id: pCount
item1, 2
item2, 1
我尝试了以下查询,但它只返回第1条记录/ 1行。
SELECT prd.*, COUNT(pc.id) pCount
FROM `product` AS prd
JOIN product_consumer pc ON pc.id = prd.id
答案 0 :(得分:1)
试试这个
SELECT pc.id, COUNT(pc.id) pCount
FROM product AS prd
JOIN product_consumer pc ON pc.id = prd.id
GROUP BY pc.id
假设您的架构是这样的:
CREATE TABLE product(
id int,
product varchar(1)
)
CREATE TABLE product_consumer(
id int,
consumer varchar(1),
pid int
)
如果您想要products
所有count
的详细信息,则需要在group by clause
中包含prd的所有属性,如下所示:
SELECT prd.id, prd.product, count(pc.pid) as pCount
FROM product AS prd
JOIN product_consumer pc ON pc.pid = prd.id
GROUP BY prd.id, prd.product, pc.pid;
请参阅此SQLFiddle
答案 1 :(得分:0)
使用GROUP BY条款
SELECT prd.id, count(pc.id) pCount
FROM product AS prd JOIN product_consumer pc ON pc.id = prd.id
GROUP BY prd.id
答案 2 :(得分:0)
实际上,如果您不需要产品名称,则无需加入
SELECT id, count(*)
FROM product_consumer
GROUP BY id;