We have these tables in PostgreSQL 12:
User -> id, name, email items -> id, user_id, description
We want to run a query to find users that have 1 item or less.
I tried using a join statement and in the WHERE clause tried to put the count of users < 1 with this query
select * from "user" inner join item on "user".id = item.user_id where count(item.user_id) < 1;
but it failed and gave me this error.
ERROR: aggregate functions are not allowed in WHERE
LINE 1: …inner join item on "user".id = item.user_id where count(item…
so im thinking the query needs to be more techincal.
Can anyone please help me with this? thanks
2
Answers
You can do:
You don’t technically need a JOIN for this. You can get all the necessary data from the
item
table withGROUP BY
. The trick is you need to useHAVING
instead ofWHERE
for aggregated data likeCOUNT()
But we can add a
JOIN
if you want to see more fields from theuser
table: