join创建了错误的结果查询

3qpi33ja  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(278)

在查询中执行求和和和左联接时,结果不再正确。这是因为在一个表中,我加入的id更常见,如何防止求和出错?
我有一张table叫 Norm ```
ID: 1 LocationID: 1 Norm: 0,22

ID: 1 LocationID: 1 Norm: 0,25

我有一张table叫 `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);

我需要连接,但希望总和是正确的,因为在第一我怎么能做到这一点?

wfypjpf4

wfypjpf41#

这将起作用:

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

fivyi3re2#

你可以试试这个

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

相关问题