2014-02-14 31 views
1
我有相同結構2個表

(會有更多),其中我將有2列參照表和另一表中的主鍵:MySQL的加入選擇從外部表名稱中細胞

TABLE 1: 
    id value  exttable extid 
    ============================= 
    1 val_1_1 0   0 
    2 val_1_2 0   0 
    3 NULL  2   5 
    4 val_1_4 0   0 
    5 val_1_5 0   0 

TABLE 2: 
    id value  exttable extid 
    ============================= 
    1 val_2_1 0   0 
    2 val_2_2 0   0 
    3 val_2_3 0   0 
    4 val_2_4 0   0 
    5 val_2_5 0   0 

我想在表1中作出選擇,其中讀取exttableextid列值並參照另一個表格。所以,我的輸出應是這樣的:

OUTPUT: 
    id val 
    ========== 
    1 val_1_1 
    2 val_1_2 
    3 val_2_5 
    4 val_1_4 
    5 val_1_5 

我知道,一個循環引用可能會導致麻煩,但我會盡量避免這種以不同的方式。

+0

是你的目標數據集正確嗎?因爲這是一個單獨的UNION – frlan

+0

一般而言,如果有多個表具有相同的列,則數據結構有問題。你應該添加一個「tableid」列,並把所有的數據放在一個表中。 –

+0

是的你是對的。在兩張桌子上有相同的結構並不聰明。其實結構不一樣,但相似,所以我簡化了它的例子。 – SetMeUp

回答

1

您應該將所有這些數據放在一個帶有額外列的表格中,我會將其稱爲「tableid」。如果你有這個,你可以這樣做:

select t.id, 
     (case when t.exttable <> 0 then t1.value else t2.value end) as value, 
     (case when t.exttable <> 0 then t1.exttable else t2.exttable end) as exttable, 
     (case when t.exttable <> 0 then t1.extid else t2.extid end) as extid 
from table t left outer join 
    table t2 
    on t.exttable = t2.tableid and 
     t.extid = t2.id; 

因爲你的數據是錯誤的格式,你可以更痛苦與union all做到這一點:

select t.id, 
     (case when t.exttable <> 0 then t1.value else t2.value end) as value, 
     (case when t.exttable <> 0 then t1.exttable else t2.exttable end) as exttable, 
     (case when t.exttable <> 0 then t1.extid else t2.extid end) as extid 
from ((select 'table1' as tableid, t.* from table1 t) union all 
     (select 'table2' as tableid, t.* from table2 t) 
    ) t left outer join 
    ((select 'table1' as tableid, t.* from table1 t) union all 
     (select 'table2' as tableid, t.* from table2 t) 
    ) t2 
    on t.exttable = t2.tableid and 
     t.extid = t2.id; 
1

我希望這會工作,否則有的一在這個查詢中需要很少的改變。 試試這個...

select * from (select id,value from TABLE 1 where value !=NULL UNION 
select TABLE 1.id,TABLE 2.value from TABLE 2,TABLE 1 where TABLE 1.value =NULL 
and TABLE 1.extid=TABLE 2.id) as results order by id 
+0

不可以,因爲表2的表名必須從單元中讀出 - 所以它是動態的。我會有更多的2個表格,所以我不能將其硬編碼爲2。 – SetMeUp