使用SUM方法和条件使用多个连接时Mysql获取错误?

时间:2016-01-09 17:39:23

标签: php mysql

第一次查询 -

SELECT 
  SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) AS `Added`
 ,SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) ) AS `Deduct`
 ,(SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) - SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) )) AS `Actual Credit Balance Client Hold` 
FROM `resellers` AS `r`
LEFT JOIN `reseller_msg` AS `rm` ON `rm`.`reseller_id` = `r`.`resellerId`
INNER JOIN `panel_login` AS`p` ON `p`.`s_no` = `r`.`resellerId`
GROUP BY `rm`.`reseller_id`
ORDER BY `r`.`resellerId` DESC 

在运行第一次查询时,它会得到正确的结果 -

username    Added   Deduct  Actual Credit Balance Client Hold   
pankaj123   1000    0       1000
soravgarg   1200    210     990

第二次查询 -

SELECT
  `r`.`reseller_uname` AS `username`
 ,SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) AS `Added`
 ,SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) ) AS `Deduct`
 ,(SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) - SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) )) AS `Actual Credit Balance Client Hold`
FROM `resellers` AS `r`
LEFT JOIN `reseller_msg` AS `rm` ON `rm`.`reseller_id` = `r`.`resellerId`
INNER JOIN `panel_login` AS`p` ON `p`.`s_no` = `r`.`resellerId`
LEFT JOIN `user_msgs` AS `um` ON `um`.`reseller_id` = `r`.`resellerId`
GROUP BY `rm`.`reseller_id`
ORDER BY `r`.`resellerId` DESC 

但是使用第二个查询会得到不正确的结果 -

username    Added   Deduct  Actual Credit Balance Client Hold   
pankaj123   1000    0       1000
soravgarg   7200    1260    5940

在第二个查询中,我只添加了另一个

连接
LEFT JOIN `user_msgs` AS `um` ON `um`.`reseller_id` = `r`.`resellerId`

在第二次查询中添加此行,结果不正确;我们也可以在第二行看到这一点。

你也可以在这里查看数据库结构 -

http://appsms.in/sql/sms_panel

1 个答案:

答案 0 :(得分:0)

INNER JOIN更改为LEFT JOIN

SELECT r.reseller_uname AS username, 
SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) AS Added,
SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) ) AS Deduct,
(SUM( IF( rm.rm_msg_type = 'In', rm.messages, 0 ) ) - SUM( IF( rm.rm_msg_type = 'Out', rm.messages, 0 ) )) AS `Actual Credit Balance Client Hold`
FROM resellers AS r 
LEFT JOIN reseller_msg AS rm ON rm.reseller_id = r.resellerId 
LEFT JOIN panel_login AS p ON p.s_no = r.resellerId      --    <-- This one
LEFT JOIN user_msgs AS um ON um.reseller_id = r.resellerId 
GROUP BY rm.reseller_id 
ORDER BY r.resellerId DESC;