与mysql中的另一个表连接后,具有相同id的多个记录提供双重数据

时间:2017-01-05 12:55:10

标签: mysql join mysqli

我正在执行下面两个表auditqueue_entry和rep_permission的查询。 表格rep_permission具有针对 rep_id 的多个记录,这导致在使用汇总功能总和后提供双倍付款金额。 请帮助我更改查询,以便提供准确的数据。

   Select aqe.rep_id, sum(aqe.payment) as aqauditcents
     From cclog.auditqueue_entry as aqe
Left Join ccconf.rep_permission 
       On aqe.rep_id = rep_permission.rep_id
    Where aqe.processedtime 
  Between "2015-11-09 00:00:00" 
      And "2015-11-10 00:00:00"
      And processedtime > 0
      And rep_permission.permission_id IN ($ids)
 Group By aqe.rep_id

例如: -

rep_permission表:

+--------+---------------+
| rep_id | permission_id |
+--------+---------------+
|  60421 |            21 |
|  60421 |           451 |
+--------+---------------+

auditqueue_entry表:

+--------+---------+
| rep_id | payment |
+--------+---------+
|  60421 |     120 |
+--------+---------+

当前输出:

+--------+--------------+
| rep_id | aqauditcents |
+--------+--------------+
|  60421 |         240  | 
+--------+--------------+

预期产出:

+--------+--------------+
| rep_id | aqauditcents |
+--------+--------------+
|  60421 |         120  | 
+--------+--------------+

请建议。

1 个答案:

答案 0 :(得分:1)

在子查询中找到所需的rep_ids然后加入

select aqe.rep_id, sum(aqe.payment) as aqauditcents
from cclog.auditqueue_entry as aqe
left join (
    select distinct rep_id from rep_permission
    where rep_permission.permission_id IN ($ids)
) rep_permission on aqe.rep_id = rep_permission.rep_id
where aqe.processedtime between "2015-11-09 00:00:00" and "2015-11-10 00:00:00"
and processedtime > 0
group by aqe.rep_id