【问题标题】:how to fetch data from 2 tables in SQL with null Entries如何使用空条目从 SQL 中的 2 个表中获取数据
【发布时间】:2021-09-15 00:35:16
【问题描述】:

我的表格看起来像这样

-- t1
id  col_1
1   Tim
2   Marta

-- t2
id  col_2
1   Tim
3   Katarina

我想要这样的结果?

--Result
id   col_1       col_2
1    Tim           Tim
2    Marta        *Null*
3   *Null*      Katarina  

如果有人知道我如何使用 SQL 做到这一点,请告诉我?

【问题讨论】:

    标签: php mysql sql inner-join union


    【解决方案1】:

    MySQL 没有 FULL OUTER JOIN,所以你需要模拟它,但要注意它是 slw

    CREATE tABLE t1(id int, col_1 varchar(50))
    
    INSERT INTO t1 VALUES (1,'Tim'),(2,'Martqa')
    
    CREATE tABLE t2(id int, col_2 varchar(50))
    
    INSERT INTO t2 VALUES (1,'Tim'),(3,'Katarina')
    
    SeLECT t1.id, t1.col_1,t2.col_2
    FROM t1 LEFT JOIN t2 USING(id)
    UNION 
    SeLECT t2.id, t1.col_1,t2.col_2
    FROM t1 RIGHT JOIN t2 USING(id)
    
    编号 | col_1 | col_2 -: | :----- | :-------- 1 |蒂姆 |蒂姆 2 |玛卡 | 3 | |卡塔琳娜
    SeLECT t1.id, t1.col_1,t2.col_2
    FROM t1 LEFT JOIN t2 USING(id)
    WHERE t1.id > 1
    UNION 
    SeLECT t2.id, t1.col_1,t2.col_2
    FROM t1 RIGHT JOIN t2 USING(id)
    WHERE t2.id > 1
    
    编号 | col_1 | col_2 -: | :----- | :-------- 2 |玛卡 | 3 | |卡塔琳娜
    SELECT * FROM
    (SeLECT t1.id, t1.col_1,t2.col_2
    FROM t1 LEFT JOIN t2 ON t1.id = t2.id 
    UNION 
    SeLECT t2.id, t1.col_1,t2.col_2
    FROM t1 RIGHT JOIN t2 ON t1.id = t2.id) t1
    WHERE id > 1
    
    编号 | col_1 | col_2 -: | :----- | :-------- 2 |玛卡 | 3 | |卡塔琳娜

    db小提琴here

    【讨论】:

    【解决方案2】:

    试试这个

    select t1.id, t1.col_1, t2.col_2
    FROM t1 LEFT OUTER JOIN t2 ON (t1.id=t2.id)
    UNION
    SELECT t2.id, t1.col_1, t2.col_2
    FROM t2 LEFT OUTER JOIN t1 ON (t2.id = t1.id)
    

    【讨论】:

      【解决方案3】:

      你想要一个full join,MySQL 不支持它一种方法是获取所有 id 并使用left join

      select *
      from (select id from t1
            union    -- on purpose to remove duplicates
            select id from t2
           ) i left join
           t1
           using (id) left join
           t2
           using (id);
      

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-01
        相关资源
        最近更新 更多