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
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With