2012-10-21 63 views
0

我有severals表,命名爲這樣的:如何合併MySQL中多選擇

table_2012_12 
table_2012_10 
table_2012_07 

都具有相同的結構:

id 
order_id 
account_id 

我知道我必須執行這些查詢:

SELECT * FROM table_2012_12 where id=1 
SELECT * FROM table_2012_12 where id=5 
SELECT * FROM table_2012_10 where id=1 
SELECT * FROM table_2012_07 where id=22 

什麼是最好的(在表演)方法使用單個查詢?

+0

在您採用下面的聯合查詢之一後,使用它們構造一個名爲'all_time_table'的新表,並在其中包含日期字段。 :) –

回答

1

UNION運營商做到這一點。請參閱:http://dev.mysql.com/doc/refman/5.6/en/union.html

SELECT * FROM table_2012_12 where id=1 
UNION ALL 
SELECT * FROM table_2012_12 where id=5 
UNION ALL 
SELECT * FROM table_2012_10 where id=1 
UNION ALL 
SELECT * FROM table_2012_07 where id=22 

通常情況下,你不應該只寫UNIONUNION ALLUNION具有連接查詢結果的效果,以及過濾掉任何重複的行。 UNION ALL將簡單地合併查詢結果,並保留所有行。這是更有效

+0

太棒了!非常感謝 – Mike

1

鑑於這種結構,你不能做任何優化,但你可以做一個union查詢:

SELECT * FROM table_2012_12 where id=1 
UNION SELECT * FROM table_2012_12 where id=5 
UNION SELECT * FROM table_2012_10 where id=1 
UNION SELECT * FROM table_2012_07 where id=22 

UNION會自動刪除重複。

1
SELECT * FROM table_2012_12 where id=1 OR id=5 
UNION ALL SELECT * FROM table_2012_10 where id=1 
UNION ALL SELECT * FROM table_2012_07 where id=22