mysql SQL中的完全连接5个不同的表

pxq42qpu  于 2023-06-04  发布在  Mysql
关注(0)|答案(1)|浏览(140)

我有5个不同的表与col1col3col5col7,和col9的ID如下:

Table 1        Table 2     Table 3     Table 4     Table 5 

col1 col2      col3 col4   col5 col6   col7 col8   col9 col10
 a    5         a    7      c    6      a    5      b     6
 b    7         b    8      f    2      c    6      c     7
 c    2         c    3      g    5      f    9      e     1
 e    5         d    7      h    8      g    3      f     5
 f    9         f    5      j    5      i    4      i     8
 g    3         g    1      k    2      k    6      
 h    6         h    9      l    6      n    1      
 j    1         i    7      n    8              
 k    5         j    4      o    3              
 m    6         k    7                      
 o    2         l    2                      
                n    5

我想加入所有的表,不管有相同的ID或没有。
连接表的结果应如下所示:

col1 col2 col4 col6 col8 col10
 a    5    7         5  
 b    7    8              6
 c    2    3    6    6    7
 d         7            
 e    5                   1
 f    9    5    2    9    5
 g    3    1    5    3  
 h    6    9    8       
 i    1    7         4    8
 j    5    4    5       
 k         7    2    6  
 l         2    6       
 m    6             
 n         5    8    1  
 o    2         3

我已经尝试了下面的查询,但似乎表2,表3,表4和表5中的任何ID都没有连接。

SELECT table1.col1, table1.col2, table2.col4, table3.col6, table4.col8, table5.col10,
FROM table1
FULL JOIN table2 ON table1.col1 = table2.col3
FULL JOIN table3 ON table1.col1 = table3.col5
FULL JOIN table4 ON table1.col1 = table4.col7
FULL JOIN table5 ON table1.col1 = table5.col9;

我应该使用什么其他的连接方式来获得上面预期的结果?

gcuhipw9

gcuhipw91#

SELECT table0.col1,
       table1.col2,
       table2.col4,
       table3.col6,
       table4.col8,
       table5.col10
FROM (
    SELECT col1 FROM table1
    UNION ALL
    SELECT col3 FROM table2
    UNION ALL
    SELECT col5 FROM table3
    UNION ALL
    SELECT col7 FROM table4
    UNION
    SELECT col9 FROM table5
    ) AS table0
LEFT JOIN table1 ON table0.col1 = table1.col1
LEFT JOIN table2 ON table0.col1 = table2.col3
LEFT JOIN table3 ON table0.col1 = table3.col5
LEFT JOIN table4 ON table0.col1 = table4.col7
LEFT JOIN table5 ON table0.col1 = table5.col9

相关问题