具有两个条件的LEFT OUTER JOIN无法正常工作

时间:2012-08-30 15:21:38

标签: mysql sql left-join

SELECT mein.person_id AS per_Id, DATE( mein.timestamp ) AS dates, SUM( nr_pos ) AS pos, SUM( nr_neg ) AS neg, SUM( nr_neu) AS neu, 
op , clo  
FROM base1.q  
LEFT JOIN base1.mein ON DATE( mein.timestamp ) = q.date  
AND mein.person_id = q.id  
WHERE mein.person_id = 1  
GROUP BY q.date, q.id  
ORDER BY mein.person_id, q.date DESC   

上面的代码应该执行以下操作: 我想从我的数据库base1加入两个表,即qmein。如果列date(mein.timestamp)和列q.date重合并且列mein.person_id和列q.id重合,则必须以联接的方式进行此操作。 我遇到的困难是,即使q没有条目,我希望date(mein.timestamp)的条目在那里,这就是我使用左外连接的原因。 不幸的是,仍有一些行已被踢出date(mein.timestamp)没有条目但q.date没有。如何管理这个以防止这些行并将这些行保留在联合表中?

谢谢!

3 个答案:

答案 0 :(得分:0)

在WHERE子句中测试LEFT JOINed列(在您的情况下为mein.person_id)时,强制该连接的行为就像它是INNER JOIN一样。相反,将该测试作为连接条件的一部分。

SELECT mein.person_id AS per_Id, DATE( mein.timestamp ) AS dates, SUM( nr_pos ) AS pos, SUM( nr_neg ) AS neg, SUM( nr_neu) AS neu, 
op , clo  
    FROM base1.q  
        LEFT JOIN base1.mein 
            ON DATE( mein.timestamp ) = q.date  
                AND mein.person_id = q.id  
                AND mein.person_id = 1  
    GROUP BY q.date, q.id  
    ORDER BY mein.person_id, q.date DESC

答案 1 :(得分:0)

您的加入应该是

LEFT JOIN base1.mein ON DATE( mein.timestamp ) = q.date  
AND mein.person_id = q.id  AND mein.person_id = 1  

答案 2 :(得分:0)

更改

WHERE mein.person_id = 1 

WHERE q.id = 1

所以你从base1.q获取q.id = 1的所有行,如果存在任何行,则从base1.mein获取与mein.timestamp和mein.person_id匹配的相应行