从两个表中选择数据作为一个表

时间:2013-01-23 15:33:08

标签: mysql sql

我有两个相似的表,想要从一个查询得到两个表的结果,结果就像一个表(行为串联,顺序为时间)

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或......?

4 个答案:

答案 0 :(得分:3)

您只需使用UNION ALL ALL - 允许重复。

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 all之间的区别在于Union all不会消除重复的行,而只是从所有符合查询细节的表中提取所有行,并将它们组合成一个表。

输出看起来像这样,

╔══════╦═══════╦═════════╗
║ 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 :(得分:1)

如果两个表的字段数相同,则可以使用:

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

UNION ALL将选择第一个查询的所有行,并与第二个查询的所有行组合。如果需要删除重复项,则应使用UNION而不是UNION ALL。 ORDER BY子句将按时间对结果行进行排序。

请参阅此处UNION子句的文档。

答案 2 :(得分:1)

http://www.w3schools.com/sql/sql_union.asp

使用带有union all的select语句来实现此目的

答案 3 :(得分:0)

使用UNION ALL,如下所示:

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
相关问题