Join problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gaz69a
    New Member
    • Sep 2008
    • 2

    Join problem

    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):
    Code:
    +------+---------+---------+
    | id_x | value_2 | value_3 |
    +------+---------+---------+
    |    1 |      70 |       9 |
    +------+---------+---------+
    How is possible to get correct result:
    Code:
    +------+---------+---------+
    | id_x | value_2 | value_3 |
    +------+---------+---------+
    |    1 |      35 |       3 |
    +------+---------+---------+
    Question is - how I should change the join to get correct values?
    Last edited by Atli; Sep 30 '08, 06:12 PM. Reason: Added [code] tags.
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    You could try using Correlated Subqueries.
    Those are basically just subqueries that reference tables from the outer query.

    For example:
    [code=mysql]
    SELECT
    t1.ID,
    (SELECT SUM(t2.value) FROM t2 WHERE t2.t1_ID_FK = t1.ID) AS 'Sum'
    FROM t1
    WHERE t1.ID = 1
    [/code]

    Comment

    • gaz69a
      New Member
      • Sep 2008
      • 2

      #3
      Thanks for your reply Atli!

      You right – we can use subqueries but then we can’t select more than one field with one subquery…

      One possible way to solve a problem is “union select” :
      [code=mysql]
      SELECT `x`.`id_x`, SUM(`x`.`value_ 2`) AS `value_2`, SUM(`x`.`value_ 3`) AS `value_3` FROM
      (
      SELECT
      `t1`.`id_x`,
      `t2`.`value_2`,
      0 AS `value_3`
      FROM `t_1` `t1`
      LEFT JOIN `t_2` `t2` ON `t1`.`id_x` = `t2`.`id_x`
      UNION
      SELECT
      `t1`.`id_x`,
      0 AS `value_2`,
      `t3`.`value_3`
      FROM `t_1` `t1`
      LEFT JOIN `t_3` `t3` ON `t1`.`id_x` = `t3`.`id_x`
      ) AS `x`
      WHERE `x`.`id_x` = 1
      GROUP BY `x`.`id_x`;
      [/code]
      Is it really so, that MySQL doesn’t have “normal” way to join multiple tables?
      Last edited by Atli; Oct 1 '08, 12:01 PM. Reason: Added [code] tags.

      Comment

      Working...