Hi,
Let’s say that we have three tables:
[CODE=mysql]
CREATE TABLE t_1 (id_x INT);
CREATE TABLE t_2 (id_x INT, value_2 INT);
CREATE TABLE t_3 (id_x INT, value_3 INT);
[/CODE]
And some data in these:
[code=mysql]
INSERT INTO t_1 VALUES(1);
INSERT INTO t_2 VALUES(1,10),(1 ,20),(1,5);
INSERT INTO t_3 VALUES(1,1),(1, 2);
[/code]
Now try to select data with this select:
[code=mysql]
SELECT `t1`.`id_x`,
SUM(`t2`.`value _2`) AS `value_2`,
SUM(`t3`.`value _3`) AS `value_3`
FROM `t_1` `t1`
LEFT JOIN `t_2` `t2` ON `t1`.`id_x` = `t2`.`id_x`
LEFT JOIN `t_3` `t3` ON `t1`.`id_x` = `t3`.`id_x`
WHERE `t1`.`id_x` = 1
GROUP BY `t1`.`id_x`;
[/code]
Result is (which is wrong):
How is possible to get correct result:
Question is - how I should change the join to get correct values?
Let’s say that we have three tables:
[CODE=mysql]
CREATE TABLE t_1 (id_x INT);
CREATE TABLE t_2 (id_x INT, value_2 INT);
CREATE TABLE t_3 (id_x INT, value_3 INT);
[/CODE]
And some data in these:
[code=mysql]
INSERT INTO t_1 VALUES(1);
INSERT INTO t_2 VALUES(1,10),(1 ,20),(1,5);
INSERT INTO t_3 VALUES(1,1),(1, 2);
[/code]
Now try to select data with this select:
[code=mysql]
SELECT `t1`.`id_x`,
SUM(`t2`.`value _2`) AS `value_2`,
SUM(`t3`.`value _3`) AS `value_3`
FROM `t_1` `t1`
LEFT JOIN `t_2` `t2` ON `t1`.`id_x` = `t2`.`id_x`
LEFT JOIN `t_3` `t3` ON `t1`.`id_x` = `t3`.`id_x`
WHERE `t1`.`id_x` = 1
GROUP BY `t1`.`id_x`;
[/code]
Result is (which is wrong):
Code:
+------+---------+---------+ | id_x | value_2 | value_3 | +------+---------+---------+ | 1 | 70 | 9 | +------+---------+---------+
Code:
+------+---------+---------+ | id_x | value_2 | value_3 | +------+---------+---------+ | 1 | 35 | 3 | +------+---------+---------+
Comment