Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count() and left join problem

I'm having a problem with the a query which displays a list of shops with the number of products associated with it. I've been playing around with left joins etc for quite a while now but to no avail. The tables have the following structures:

Shops table containing columns: id, name

Products table containing columns: id, name, status, shop

The query is as follows:

select s.name
       , p.name
       , count(p.id) 
from   Product as p 
       left join Shop as s on p.shop=s.id
where  p.status <> '8796107276379'
group by 
       s.id

I'm not getting the shops which have 0 products. How can I achieve this please?

The underlying database is MySQL.

Thanks! Krt_Malta

like image 917
Krt_Malta Avatar asked Feb 13 '11 10:02

Krt_Malta


People also ask

Can we use count in joins in SQL?

In this short tutorial, you have seen how the COUNT/GROUP BY/JOIN combination can be used in SQL to aggregate entries across multiple tables. While a GROUP BY query can accomplish this simply enough when working with just one table, the situation can become more complex when working across multiple tables.

Why have I got an increased row count after LEFT join?

Left Outer Join returns all of the rows in the current data and all the data from the matching rows in the joined data, adding rows when there is more than one match. This can result in an expanded row count.

Why does LEFT join return NULL?

The LEFT JOIN command returns all rows from the left table, and the matching rows from the right table. The result is NULL from the right side, if there is no match.

Does LEFT join take NULL values?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.


2 Answers

You need SHOP on the LEFT side, since the right side is the one that may not have data, in this case PRODUCT.

Not only that, you need the WHERE condition as a LEFT-JOIN ON condition, so that it joins to products on the status condition and just discounts the product (while keeping shop) even if the status is not desired.

select s.name
       , p.name
       , count(p.id) 
from   Shop as s
       left join Product as p on p.shop=s.id AND p.status <> '8796107276379'
group by 
       s.id, p.name
like image 149
RichardTheKiwi Avatar answered Oct 01 '22 11:10

RichardTheKiwi


select s.name
       , p.name
       , count(p.id) 
from   Shop as s 
       left join Product as p on s.id=p.shop
where  p.status <> '8796107276379'
group by 
       s.id
like image 27
ibrahim sandallı Avatar answered Oct 01 '22 10:10

ibrahim sandallı