Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid because it is not contained in an aggregate function or the group by clause

Tags:

sql

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.

like image 403
Jerodev Avatar asked May 02 '12 17:05

Jerodev


People also ask

Which clause is not used with aggregate functions?

You cannot use aggregate functions in a WHERE clause or in a JOIN condition.

Is invalid in the ORDER BY clause because?

invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

What happens when you use an aggregate function with a 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.

Why WHERE clause Cannot be used with the aggregate functions?

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.


1 Answers

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.

like image 188
Andriy M Avatar answered Oct 04 '22 19:10

Andriy M