8

我想创建一个从产品表中获取产品的查询,它是类型表中的类型和类别以及产品中歌曲的数量。但不知何故,这个查询会引发错误。它从我添加时开始count(n.name)

SELECT p.name, p.publisher, p.description, p.price, p.picture
     , p.releasedate, t.type, t.category, count(n.name) AS songs
  FROM Products p
 INNER JOIN ProductType t ON (p.type_id = t.id)
 INNER JOIN Songs n ON (p.id = n.product_id)

我得到的错误是

列“Products.name”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

4

2 回答 2

6

仅对行进行分组Songs,然后加入聚合数据而不是Songs正确的表:

SELECT p.name, p.publisher, p.description, p.price, p.picture
     , p.releasedate, t.type, t.category, n.songs
  FROM Products p
 INNER JOIN ProductType t ON (p.type_id = t.id)
 INNER JOIN (
   SELECT
     product_id,
     COUNT(n.name) AS songs
   FROM Songs
   GROUP BY product_id
 ) n ON (p.id = n.product_id)

这样,您将避免将几乎所有输出列添加到GROUP BY子句中,而您必须在问题中发布的查询中执行此操作。

于 2012-05-02T23:03:51.837 回答
0
SELECT p.name, p.publisher, p.description, p.price, p.picture, p.releasedate, t.type, t.category, count(1) AS songs
                    FROM Products p
                    INNER JOIN ProductType t ON (p.type_id = t.id)
                    INNER JOIN Songs n ON (p.id = n.product_id)
GROUP BY p.name, p.publisher, p.description, p.price, p.picture, p.releasedate, t.type, t.category
于 2012-05-02T17:52:39.323 回答