簡體   English   中英

左外部聯接到兩個表

[英]Left outer join to two tables

我有一個表1與表2具有一對多關系。表1也與表3具有一對多關系。

我想合並聯接的結果,但我得到的只是重復的值

結構如下:

table 1
reportnumber
1
2
3

table 2
reportnumber  col1
1              a
1              b
2              c
3              a

table 3
reportnumber  col2
1              x
1              y
1              z
2              w

預期結果集

reportnumber   col1   col2
1                a      x
1                b      y
1                       z
2                c      w
3                a

我敢肯定這可能與左外部聯接,但我只是不能正確的語法

有什么線索嗎?

這就是我正在嘗試的

select * from table1 a 
left outer join table2 b on a.reportnumber=b.reportnumber
left outer join table3 on a.reportnumer=c.reportnumber 

但是結果看起來像這樣

reportnumber   col1   col2
1               a       x
1               a       y
1               a       z
1               b       x
1               b       y
1               b       z
...

這在MySQL中並不容易,但是您可以使用變量來實現。 這有一點做的一個join 或者,它與join有很多關系,但是您沒有正確的join鍵,也沒有full outer join

解決方案是用數據列枚舉每個表中的行。 然后使用枚舉和reportnumber

select reportnumber, max(col1) as col1, max(col2) as col2
from ((select t2.reportnumber, col1, null as col2, @rn2 := @rn2 + 1 as rn
       from table2 t2 cross join
            (select @rn2 := 0) const
      ) union all
      (select t3.reportnumber, null, t3.col2, @rn3 := @rn3 + 1 as rn
       from table3 t3 cross join
             (select @rn3 := 0) const
      )
     ) t
group by reportnumber, rn;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM