我想创建一个查询,从产品表中获取产品,从类型表中获取类型和类别以及产品上的歌曲数量。
但不知何故,此查询会引发错误。它是在我添加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子句中。
答案 0 :(得分: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
子句中,您必须在问题中发布的查询中进行此操作。
答案 1 :(得分: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