使用join运行查询时结果加倍

时间:2014-01-08 07:39:32

标签: mysql join

我正在使用此查询从3个表中获取数据。

SELECT sum( tu.filesize ) AS totalSize, tu.sender, tu.receiver, tu.valid_time, group_concat( tu.filename ) AS files, tu.file_path, us.uid temp_id, tu.unique_key, tu.uid user_id, tu.file_encryption, t_l.encryption_password
FROM tbl_uploads tu
LEFT JOIN tbl_users us ON us.id = tu.uid
LEFT JOIN tbl_logs t_l ON t_l.u_key = tu.unique_key
WHERE date( tu.valid_time ) = '2014-01-09'
AND tu.sender <> ''
GROUP BY tu.unique_key

但没有得到预期的结果,因为tbl_uploadstbl_logs几乎具有名称filesize, filename的相同字段,因此当我运行此查询时,我获得了双重文件大小{{1}和文件; filesize应为462804

1 个答案:

答案 0 :(得分:0)

为了避免来自tbl_logs的双行,请尝试:

SELECT sum( tu.filesize ) AS totalSize, tu.sender, tu.receiver, tu.valid_time, group_concat( tu.filename ) AS files, tu.file_path, us.uid temp_id, tu.unique_key, tu.uid user_id, tu.file_encryption, t_l.encryption_password
FROM tbl_uploads tu
    LEFT JOIN tbl_users us ON us.id = tu.uid
    LEFT JOIN (SELECT u_key, encryption_password FROM tbl_logs GROUP BY u_key, encryption_password) AS t_l ON t_l.u_key = tu.unique_key
WHERE date( tu.valid_time ) = '2014-01-09'
AND tu.sender <> ''
GROUP BY tu.unique_key