2012-11-22 46 views
0

有沒有什麼方法可以使用結果來指定表加入?使用sql結果指定要加入的表

我想這樣做

SELECT id, some_number, ... FROM sometable NATURAL JOIN someothertable_$some_number; 

我知道,有沒有這樣的關係代數,所以可能我不會成功,我只是想問問是肯定的。

我不想使用任何SQL腳本。

+2

存儲過程是否計爲「SQL腳本」? – AndreKR

+0

是的,我的意思是存儲過程抱歉 –

回答

1

Runnable的例子這裏:http://sqlfiddle.com/#!2/5e92c/36

代碼設置表這個例子:

create table if not exists someTable 
(
    someTableId bigint not null auto_increment 
    , tableId int not null 
    , someOtherTableId bigint not null 

    , primary key (someTableId) 
    , index (tableId, someOtherTableId) 
); 

create table if not exists someOtherTable_$1 
(
    someOtherTableId bigint not null auto_increment 
    , data varchar(128) character set utf8 

    , primary key (someOtherTableId) 
); 

create table if not exists someOtherTable_$2 
(
    someOtherTableId bigint not null auto_increment 
    , data varchar(128) character set utf8 

    , primary key (someOtherTableId) 
); 

insert sometable (tableId, someOtherTableId) values (1, 1); 
insert sometable (tableId, someOtherTableId) values (1, 2); 
insert sometable (tableId, someOtherTableId) values (2, 2); 
insert sometable (tableId, someOtherTableId) values (2, 3); 

insert someothertable_$1(data) values ('table 1 row 1'); 
insert someothertable_$1(data) values ('table 1 row 2'); 
insert someothertable_$1(data) values ('table 1 row 3'); 

insert someothertable_$2(data) values ('table 1 row 1'); 
insert someothertable_$2(data) values ('table 1 row 2'); 
insert someothertable_$2(data) values ('table 1 row 3'); 

靜態解

這裏有一個解決方案,如果你的表是固定的(例如,在這個例子中你只有其他表1和2 /你不需要添加新表時自動更改代碼):

select st.someTableId 
, coalesce(sot1.data, sot2.data) 
from someTable st 
left outer join someOtherTable_$1 sot1 
on st.tableId = 1 
and st.someOtherTableId = sot1.someOtherTableId 
left outer join someOtherTable_$2 sot2 
on st.tableId = 2 
and st.someOtherTableId = sot2.someOtherTableId; 

動態的解決方案

如果表的數量可以在運行時改變你需要編寫動態SQL。注意:隨着每一張連續的桌子,你將會受到性能影響。我不會推薦這個用於生產系統;但這是一個有趣的挑戰。如果您可以描述您的工具集&您希望實現的目標,我們可能會向您提供一些更合適的前進方向。

select group_concat(distinct ' sot' , cast(tableId as char) , '.data ') 
into @coalesceCols 
from someTable; 

select group_concat(distinct ' left outer join someOtherTable_$', cast(tableId as char), ' sot', cast(tableId as char), ' on st.tableId = ', cast(tableId as char), ' and st.someOtherTableId = sot', cast(tableId as char), '.someOtherTableId ' separator '') 
into @tableJoins 
from someTable; 

set @sql = concat('select someTableId, coalesce(', @coalesceCols ,') from someTable st', @tableJoins); 

prepare stmt from @sql; 
execute stmt; 
+0

PS。如果你想獲得由動態SQL獲得的結果,但不想要腳本(即如你的問題所述),我不相信這是可能的。你可以採取的方法是將你的SomeOtherTables合併到一個tableId列中的表中,然後在該列上創建一個索引。即代替'someOtherTable1'和'someOtherTable2',你有'selectOther someThereTable where tableId = 1'和'select * from someOtherTable where tableId = 2'。 – JohnLBevan