Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

mysql - (My)SQL full join with three tables

I have tree tables

ID    A
-----------
1     10

ID    B
-----------
1     20
2     30

ID    C
-----------
2     40
3     50

Can anybody please tell how to make a view or query prints like this?

ID     A      B      C      R (A + B - C)
-----------------------------------
1     10     20      0     30
2      0     30     40    -10
3      0      0     50    -50

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I know there is no full outer join in MySql. So, to do what you require you should get distinct IDs in derived table and left join original tables:

select ids.id,
       ifnull(table1.A, 0) A,
       ifnull(table2.B, 0) B,
       ifnull(table3.C, 0) C,
       ifnull(table1.A, 0) + ifnull(table2.B, 0) - ifnull(table3.C, 0) R
  from 
  (
    select id
      from table1
    union
    select id
      from table2
    union
    select id
      from table3
  ) ids
  left join table1
    on ids.id = table1.id
  left join table2
    on ids.id = table2.id
  left join table3
    on ids.id = table3.id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...