Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to include the COUNT of associations in a SQL query?

Say I have a [Products] table, and a [Products.record] can have many [Sales.records] associated with it.

I want to have a single dataset that gives me number of sales a product has. Of course a product can have zero sales.

The first version of my query looks like this:

SELECT products.*,COUNT(*) as num_of_sales
LEFT OUTER JOIN sales ON sales.product_id = products.id
GROUP BY products.id

The problem of course is that this query can't distinguish between Products that have had 1 sale and 0 sales.

So, how can I get this very simple dataset?

like image 656
andy Avatar asked May 17 '13 00:05

andy


1 Answers

don't use COUNT(*) but instead, COUNT(sales.product_id).

SELECT  products.*,
        COUNT(sales.product_id) as num_of_sales
        LEFT OUTER JOIN sales 
            ON sales.product_id = products.id
GROUP   BY products.id

As a sidenote, you should specify all the non-aggregated columns in the GROUP BY clause.

like image 150
John Woo Avatar answered Nov 10 '22 06:11

John Woo