1
votes

I have a Products table and a ProductionReport table in my database.

The ProductionReport table captures weekly production information for each product. My app will report on this information.

Table structures

ProductionReport

productionreportid, productid, date, qty
1, 1, 2013-04-08, 50
2, 2, 2013-04-08, 12

Products

productid, productname
1, Skin cream
2, Peanut Oil
3, Bath Salts
4, Shampoo

My page uses a gridview that will list all products (SELECT productid, productname FROM Products) and join in the ProductionReport table so as to display a list of all products and production values for the week that user can update.

My problem is the sql query to populate the GridView. It currently only gets rows where there is a joined value in both tables:

SELECT pro.productname, pr.productionreportid, IFNULL(pr.qty, 0) qty
FROM Products pro
LEFT JOIN ProductionReport pr ON pro.productid = pr.productid
WHERE DATE(pr.date) = '2013-04-08'

So, given the above described data, I'm expecting to get the following resultset back

Skin Cream, 1, 50
Peanut Oil, 2, 12
Bath Salts, 0, 0
Shampoo, 0, 0

Unfortunately, all I'm getting back is the first 2 rows. I believe that's because of the WHERE clause targeting a column in the joined table. If that's the case, it's clearly a serious flaw in my logic, but I don't know what to do about it.

Any suggestions?

2

2 Answers

2
votes

Try this

  SELECT  
     pro.productname, 
     pr.productionreportid, 
     IFNULL(pr.qty, 0) qty
  FROM 
    Products pro  
  LEFT JOIN ProductionReport pr  
    ON pro.productid = pr.productid 
    AND DATE(pr.date) = '2013-04-08'

Basically move the date condition from WHERE clause to the JOIN clause

0
votes

You are correct in that DATE(pr.date) = '2013-04-08' won't match if pr.date is null.

You can change it to something like pr.date is null or date(pr.date) = '2013-04-08'