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
加入两个表,即q
和mein
。如果列date(mein.timestamp)
和列q.date
重合并且列mein.person_id
和列q.id
重合,则必须以联接的方式进行此操作。
我遇到的困难是,即使q
没有条目,我希望date(mein.timestamp)
的条目在那里,这就是我使用左外连接的原因。
不幸的是,仍有一些行已被踢出date(mein.timestamp)
没有条目但q.date
没有。如何管理这个以防止这些行并将这些行保留在联合表中?
谢谢!
答案 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匹配的相应行