I would like to create a query that gets a product from the product table, it's type and category from the type table and the count of songs on the product.
But somehow this query throws an error. It started when I added 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)
The error I get is
Column 'Products.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
You cannot use aggregate functions in a WHERE clause or in a JOIN condition.
invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
The GROUP BY clause is normally used along with five built-in, or "aggregate" functions. These functions perform special operations on an entire table or on a set, or group, of rows rather than on each row and then return one row of values for each group.
We cannot use the WHERE clause with aggregate functions because it works for filtering individual rows. In contrast, HAVING can works with aggregate functions because it is used to filter groups.
Group only Songs
rows, then join the aggregated data instead of the Songs
table proper:
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)
That way you'll avoid adding almost all your output columns to the GROUP BY
clause, which you would have to do in the query posted in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With