2012-07-10 4 views
5

に参加し、私は木のテーブルはフル(私の)SQLには3つのテーブル

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

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

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

を持っている誰もがこのようなビューまたはクエリプリントを作る方法を教えてくださいことはできますか?

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

ありがとうございます。

+1

をお試しくださいいくつかの制限があります。 – Lion

+0

'view'は必須ではありません。インスタントクエリーもOKです。 – TaeL

答えて

7

私の知る限り、MySqlに完全な外部結合はありません。だから、あなたが派生テーブルに個別のIDを取得し、元のテーブルを結合左なければならない必要が何をすべきか:あなたはそこ `view`を作成したい場合は

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 
0

この

select t1.ID, t1.A,t2.B,t3.C,t1.A+t2.B-t3.C as R 
    from tableA t1 
    full outer join tableB t2 on t1.id =t2.id 
    full outer join tableC t3 on t1.id =t3.id 
0
select coalesce(a.Id, b.Id, c.Id) ID, 
     case when a.A > 0 then a.A else 0 end, 
     case when b.B > 0 then b.B else 0 end, 
     case when c.C > 0 then c.C else 0 end, 
     ifnull(a.A, 0) + ifnull(b2.B, 0) - ifnull(c.C, 0) R 
from tableA a 
right outer join tableB b on a.id = b.id 
right outer join tableC c on b.id = c.id; 
関連する問題