2

I have two tables that look like these:

users:
    id int unsigned auto_increment,
    primary key(id),
    [...]

product:
    id int unsigned auto_increment,
    seller id int unsigned auto_increment,
    primary key(id),
    foreign key(seller) references users(id)
    [...]

I want to have a list of users with all of their attributes and the amount of products each user has. I tried the following:

select u.id, [...], count(p.id) from users u, products p where p.seller=u.id and [...]

This, however gives me the following error:

ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'db.u.id'; this is incompatible with sql_mode=only_full_group_by

What would be the proper way of accomplishing the wanted result? And why does this not work?

l'arbre
  • 719
  • 2
  • 10
  • 29

5 Answers5

1

Use LEFT JOIN and GROUP BY to get the result you need. Moreover, all the attributes from user has to be part of GROUP BY clausula.

SELECT u.id,  [...], count(p.id) from users u
LEFT JOIN products p where p.seller=u.id
GROUP BY u.id, [...]

The error says that you can not mix aggregate functions and attributes behind SELECT if you do not have the GROUP BY clausula.

Radim Bača
  • 10,646
  • 1
  • 19
  • 33
1

A correlated subquery might be the simplest approach:

select u.*,
       (select count(*) from products p where p.seller = u.id) as num_products
from users u;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

You are aggregating data (count(p.id)). You are not using GROUP BY to get aggregates per some group, so you get only one result row with the aggregates.

But you also select u.id. Which one? There are many different u.id in the table, but you'll only get one result row. The DBMS expects you to tell it which one you want, e.g. MAX(u.id).

If you want to select user data, select from users. If you want to get the number of products, select them in a subquery (which is most easily done in the select clause, but can also be done in the from clause).

select
  u.*,
  (select count(*) from product p where p.seller = u.id) as number_of_products
from users u;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73
0

Here is the correct query you can try:

ASCII

SELECT u.id, [...], COUNT(p.id) FROM users u JOIN products p ON u.id=p.seller GROUP BY p.seller;

NON-ASCII

SELECT u.id, [...], COUNT(p.id) FROM users u, products p WHERE u.id=p.seller GROUP BY p.seller;
Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22
0

Use ANY_VALUE for non aggregated columns. In your example, the non aggregated column was db.u.id (see the error message). So, you should use:

select ANY_VALUE(u.id), [...], count(p.id) 
from users u, products p 
where p.seller=u.id and [...]
group by [...]

More details here.

Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88