MySQL: FULL OUTER JOIN - How do I merge one column?

后端 未结 3 1000
一个人的身影
一个人的身影 2020-12-08 01:01

I have a question regarding a FULL OUTER JOIN in MySQL. I have two (or more tables):

table1      table2
id  value   id  value2
1   a       1   b
2   c       3   d         


        
相关标签:
3条回答
  • 2020-12-08 01:36

    For what I think you are trying to do, I would suggest using a FULL OUTER JOIN instead:

    SELECT ISNULL(t1.id, t2.id) AS id, t1.value1, t2.value2
    FROM table1 t1
    FULL OUTER JOIN table2 t2 ON t1.id = t2.id
    
    0 讨论(0)
  • 2020-12-08 01:39
    SELECT 
    COALESCE(t1.id, t2.id) as id,
    t1.value1,
    t2.value2
    FROM table1 t1
    FULL JOIN table2 t2 ON t1.id = t2.id;
    
    0 讨论(0)
  • 2020-12-08 01:45

    Use:

        SELECT t1.id,
               t1.value,
               t2.value2 
          FROM table1 t1
     LEFT JOIN table2 t2 ON t2.id = t1.id
    UNION
        SELECT t2.id,
               t1.value,
               t2.value2
          FROM TABLE1 t1
    RIGHT JOIN TABLE2 t2 ON t2.id = t1.id
    

    The UNION operator removes row/record duplicates, so you have to define/list the columns appropriately.

    Scripts:

    DROP TABLE IF EXISTS `example`.`table1`;
    CREATE TABLE  `example`.`table1` (
      `id` int(10) unsigned NOT NULL default '0',
      `value` varchar(45) NOT NULL default ''
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    INSERT INTO table1 VALUES (1, 'a'), (2, 'c'), (3, 'e');
    
    DROP TABLE IF EXISTS `example`.`table2`;
    CREATE TABLE  `example`.`table2` (
      `id` int(10) unsigned NOT NULL default '0',
      `value2` varchar(45) NOT NULL default ''
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    INSERT INTO table2 VALUES (1, 'b'), (3, 'd'), (4, 'f');
    

    Edit: Fixed line above

    0 讨论(0)
提交回复
热议问题