联接创建错误的结果查询

时间:2018-09-12 10:32:22

标签: mysql sql join sum left-join

当我在查询中进行求和和左连接时,结果不再正确。这是因为在一个表中,我加入的ID更常见,如何防止总和出错?

我有一个名为Norm的表

ID: 1  LocationID: 1   Norm: 0,22

ID: 1  LocationID: 1   Norm: 0,25

我有一个名为Hour

的表
ID: 1   LocationID: 1

ID: 2   LocationID: 1

ID: 3   LocationID: 1

查询:

SELECT N.LocationID, SUM(N.Norm) FROM Norm N

结果:

LocationID: 1   Sum(N.Norm): 0,47

查询:

SELECT N.LocationID, SUM(N.Norm) FROM Norm N LEFT JOIN Hour H ON 
N.LocationID = H.LocationID

结果:

LocationID: 1 Sum(N.Norm): 1,41

脚本:

CREATE TABLE Norm` ( `ID` INT NOT NULL , `LocationID` INTNOT NULL , 
`Norm` DECIMAL(10,2) NOTNULL );

INSERT INTO `Norm`(`ID`, `LocationID`, `Norm`) 
VALUES (1,1, 0.22);

INSERT INTO `Norm`(`ID`, `LocationID`, `Norm`) 
VALUES (2,1, 0.25)


CREATE TABLE `Hour` ( `ID` INT NOT NULL , `LocationID` INTNOT NULL );

INSERT INTO `Hour`(`ID`, `LocationID`) VALUES (1, 1);
INSERT INTO `Hour`(`ID`, `LocationID`) VALUES (2, 1);
INSERT INTO `Hour`(`ID`, `LocationID`) VALUES (3, 1);

我需要连接,但是希望总和正确,如第一个我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以尝试这个

   SELECT N.LocationID
        , SUM(N.Norm) 
     FROM Norm N 
LEFT JOIN (SELECT distinct locationid FROM Hour ) AS H 
       ON N.LocationID = H.LocationID
 GROUP BY N.LocationID

答案 1 :(得分:1)

这将起作用:

SELECT N.LocationID,(select sum(norm) from norm) FROM Norm N LEFT JOIN Hour H ON 
N.LocationID = H.LocationID group by N.LOCATIONID;