简体   繁体   English

从一个表中选择联接表中条件所在的所有行

[英]Selecting all rows from one table where condition in joined table

I have a Products table and a ProductionReport table in my database. 我的数据库中有一个Products表和一个ProductionReport表。

The ProductionReport table captures weekly production information for each product. ProductionReport表捕获每个产品的每周生产信息。 My app will report on this information. 我的应用程序将报告此信息。

Table structures 表结构

ProductionReport ProductionReport

productionreportid, productid, date, qty productionreportid,productid,日期,数量
1, 1, 2013-04-08, 50 1,1,2013-04-08,50
2, 2, 2013-04-08, 12 2,2,2013-04-08,12

Products 制品

productid, productname 产品编号,产品名称
1, Skin cream 1,护肤霜
2, Peanut Oil 2,花生油
3, Bath Salts 3,沐浴盐
4, Shampoo 4,洗发水

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. 我的页面使用一个gridview,该视图将列出所有产品( SELECT productid, productname FROM Products )并加入ProductionReport表,以便显示用户可以更新的一周的所有产品和生产值的列表。

My problem is the sql query to populate the GridView. 我的问题是用于填充GridView的SQL查询。 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 护肤霜1,50
Peanut Oil, 2, 12 花生油2,12
Bath Salts, 0, 0 沐浴盐,0,0
Shampoo, 0, 0 洗发水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. 我相信这是因为WHERE子句定位了联接表中的一列。 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? 有什么建议么?

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 基本上将日期条件从WHERE子句移到JOIN子句

You are correct in that DATE(pr.date) = '2013-04-08' won't match if pr.date is null. 您是正确的,如果pr.date为null,则DATE(pr.date) = '2013-04-08'将不匹配。

You can change it to something like pr.date is null or date(pr.date) = '2013-04-08' 您可以将其更改为pr.date is null or date(pr.date) = '2013-04-08'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM