LEFT JOIN +多个WHERE子句

时间:2014-04-11 08:49:38

标签: mysql sql date join

我在编写SQL查询时遇到了麻烦。我将通过我的SQL查询解释:

SELECT p.Code, p.Name, SUM(h.PA = 1) AS PA, SUM(h.PB = 1) AS PB, 
    SUM(h.PG = 1) AS PG, SUM(h.GoedkeuringDoorNew = 'GF') AS GF,
    SUM(h.GoedkeuringDoorNew = 'SB') AS SB, 
    SUM(h.GoedkeuringDoorNew = 'VIA') AS VIA, sum(h.Blanco) AS Blanco
FROM psthostess p
LEFT JOIN `psttodo-uit` h ON h.`Hostess Code` = p.Code
WHERE p.Indienst = 1 AND DATE(h.`afgewerkt tablet datum`) = CURDATE()
GROUP BY p.Code, p.Name

正如您所看到的,我有Indienst = 1date = today的WHERE clausule。我做了一个LEFT JOIN所以我得到了所有的字段(也是null)。我已经添加了AND DATE(h.afgewerkt tablet datum) = CURDATE()。所以在我获得18行之前,现在我只得到一个,因为他也检查了日期。

但我想要18行,也是p.Indienst = 1但没有DATE = CURDATE的行。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

AND DATE(h. afgewerkt平板电脑数据) = CURDATE()移至ON子句:

SELECT p.Code, p.Name, SUM(h.PA = 1) AS PA, SUM(h.PB = 1) AS PB, 
    SUM(h.PG = 1) AS PG, SUM(h.GoedkeuringDoorNew = 'GF') AS GF,
    SUM(h.GoedkeuringDoorNew = 'SB') AS SB, 
    SUM(h.GoedkeuringDoorNew = 'VIA') AS VIA, sum(h.Blanco) AS Blanco
FROM psthostess p
LEFT JOIN `psttodo-uit` h ON h.`Hostess Code` = p.Code
AND DATE(h.`afgewerkt tablet datum`) = CURDATE()
WHERE p.Indienst = 1 
GROUP BY p.Code, p.Name

答案 1 :(得分:0)

好吧,如果你想要所有的记录,还有那些今天没有记录的记录。作为日期,你为什么要在今天过滤?只要删除该条款,你就可以了。或者,这是非常荒谬的,因为它与删除extra子句相同,将WHERE更改为:

WHERE (p.Indienst = 1 AND DATE(h.`afgewerkt tablet datum`) = CURDATE())
    OR (p.Indienst = 1 AND DATE(h.`afgewerkt tablet datum`) != CURDATE())