2013-01-23 241 views
2

我有兩個類似的表,並想從兩個表中包含一個表中的結果,一個查詢得到的結果(行作爲串聯和順序與時間)從兩個表作爲一個表中選擇數據

MYTABLE1 :

time name Comment 
------------------------- 
45  asd  testasd 
49  gas  testgas 
50  has  testhas 
96  bag  testbag 

MyTable2:

time name Comment 
------------------------- 
48  hjasf bigasd 
54  adg  biggas 
65  zxx  bighas 
115  cxx  bobbag 
131  xxb  bobhas 

結果:

time name Comment 
------------------------- 
45  asd  testasd 
48  hjasf bigasd 
49  gas  testgas 
50  has  testhas 
54  adg  biggas 
65  zxx  bighas 
96  bag  testbag 
115  cxx  bobbag 
131  xxb  bobhas 

我嘗試這樣做,但不知道,我必須使用JOIN或UNION還是...?

+0

我編輯的問題解決了,因爲我不能選擇接受低於15分鐘一個答案。 – Root125

回答

3

你只需要使用UNION ALLALL - 允許重複

SELECT time, name, Comment FROM table1 
UNION ALL 
SELECT time, name, Comment FROM table2 
ORDER BY time 

UNION命令用於從兩個表中選擇相關的信息,多像JOIN命令一樣。但是,使用UNION命令時,所有選定的列需要具有相同的數據類型。使用UNION時,只會選擇不同的值。

UNION ALL命令等同於UNION命令,不同之處在於UNION ALL選擇所有值。

Union和Union的區別在於Union不會消除重複的行,而只是從所有適合您的查詢細節的表中抽取所有行並將它們組合到一個表中。

輸出將這個樣子,

╔══════╦═══════╦═════════╗ 
║ TIME ║ NAME ║ COMMENT ║ 
╠══════╬═══════╬═════════╣ 
║ 45 ║ asd ║ testasd ║ 
║ 48 ║ hjasf ║ bigasd ║ 
║ 49 ║ gas ║ testgas ║ 
║ 50 ║ has ║ testhas ║ 
║ 54 ║ adg ║ biggas ║ 
║ 65 ║ zxx ║ bighas ║ 
║ 96 ║ bag ║ testbag ║ 
║ 115 ║ cxx ║ bobbag ║ 
║ 131 ║ xxb ║ bobhas ║ 
╚══════╩═══════╩═════════╝ 
1

如果兩個表具有相同的字段數,你可以這樣做:

SELECT * from MyTable1 
UNION ALL 
SELECT * from MyTable2 
ORDER BY time 

UNION ALL會選擇第一個查詢的所有行,所有的第二個查詢的行合併。如果你需要刪除重複,你應該使用UNION而不是UNION ALL。 ORDER BY子句將按時間順序排列結果行。

請參閱文檔UNION此處。

0

使用所有如下一個UNION:

SELECT `time`, `name`, `Comment` FROM `MyTable1` 
UNION ALL 
SELECT `time`, `name`, `Comment` FROM `MyTable2` 

要按時間嘗試訂購

SELECT * FROM (
SELECT `time`, `name`, `Comment` FROM `MyTable1` 
UNION ALL 
SELECT `time`, `name`, `Comment` FROM `MyTable2` 
) AS `Result` ORDER BY `time` ASC 
相關問題