0

我对 SQL 很陌生,不知道我的查询有什么问题。请指导

我有 2 个表 product 和 product_consumer 1 到 m 关系。我想获取所有产品和每种产品的消费者数量。

这就是我要的:

id:    pCount
item1, 2
item2, 1

我尝试了以下查询,但它只返回第一条记录/1 行。

SELECT prd.*, COUNT(pc.id) pCount 
FROM `product` AS prd 
JOIN product_consumer pc ON pc.id = prd.id
4

3 回答 3

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
)

如果你想要所有的细节,productscount需要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

于 2013-10-27T13:56:35.537 回答
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
于 2013-10-27T13:59:11.223 回答
0

其实如果你不需要产品名称就不需要加入

SELECT id, count(*)
FROM product_consumer
GROUP BY id;
于 2013-10-27T14:02:32.067 回答