views:

204

answers:

3

I have a query similar to the following:

SELECT users.id FROM users LEFT JOIN sales ON installations.customer = users.id

What I would like to say is something like "WHERE count(sales.id) > 4" - meaning that if the user has more than 4 sales assoc with them. I am not sure if I am going about this the wrong way or not though

+4  A: 
select
    users.id

from users

join sales on /* your join condition here */

group by users.id

having count(sales.id) > 4

This will group all of the sales by user, then return only those sales that have more than four records in the sales table.

I didn't duplicate your join condition from above because it didn't seem to make much sense, as it's referencing tables that aren't in your query anywhere.

Adam Robinson
Oh yeah I meant to join the sales in both, this works though thank you!
kilrizzy
A: 

I think you want something similar to this

select users.id, count(sales.id)
from users
LEFT JOIN sales ON installations.customer = users.id
group by users.id
having count(Sales.id) > 5
Jay
A: 

You need to use "group by" and "having" clause.

Try

SELECT users.id FROM users LEFT JOIN sales ON installations.customer = users.id GROUP BY users.id HAVING count(sale.id) > 4

See here for more GROUPBY on W2C

NawaMan