我有两张桌子: terems 和 logs1015 。
需要根据类似的“哈希”行将 logs1015 中的数据添加到 terems 。
如果' SUM(insum)'或' SUM(outsum)大于0,此查询正常工作。
但是,如果 logs1015 不包含具有此类“哈希”的数据,则查询结果为空。
错误是什么?感谢
SELECT terems.*,
SUM(insum) as firstsum ,
SUM(outsum) as secondsum
FROM terems
LEFT JOIN logs1015 USING(hash)
WHERE owner='1'
AND (type='stat')
AND (time BETWEEN 1445904000 AND 1445990400)
GROUP BY name
LIMIT 1000
表格结构
*terems*: id(int),hash(varchar),name(varchar),owner(int)
*logs1015*: id(int),hash(varchar),type(varchar),insum(int),outsum(int),time(varchar)
答案 0 :(得分:1)
当(左)外连接时,必须在连接条件中将where子句放在外表上,否则你说它在连接后必须存在。然后你隐含地把它变成了一个内连接。
还可以在表格上使用别名,以便轻松发现这些错误。
示例:
SELECT t.name,
SUM(l.insum) as firstsum ,
SUM(l.outsum) as secondsum
FROM terems t
LEFT JOIN logs1015 l ON t.hash = l.hash
AND (l.type='stat')
WHERE t.owner='1'
AND (t.time BETWEEN 1445904000 AND 1445990400)
GROUP BY t.name
LIMIT 1000
答案 1 :(得分:0)
工作解决方案:
"SELECT t.*,
SUM(l.insum) as firstsum ,
SUM(l.outsum) as secondsum
FROM terems t
LEFT JOIN logs1015 l ON
t.hash = l.hash
AND (l.type='stat')
AND (l.time BETWEEN $fromstamp AND $tostamp)
WHERE t.owner='$userid'
GROUP BY t.name
LIMIT 1000";
非常感谢!