如何绑定来自不同 MySQL 查询的行?

Mat*_*ert 2 mysql sql

我想将源自另一个 SQL 查询(不同表)的几行添加到查询结果中。例如:

SELECT mycol from mytable 

# returns 
mycol
1
4
6
SELECT anothercol from anothertable
#returns
anothercol
3
8
9
Run Code Online (Sandbox Code Playgroud)

我想获得的是:

myresult
1
4
6
3
8
9
Run Code Online (Sandbox Code Playgroud)

目前我使用统计软件包进行这种操作,但我想知道在 MySQL 中是否有可能。合并来自不同来源的时间序列时通常需要它。有没有 SQL 方法来做到这一点?

Mar*_*ois 5

使用 UNION 语句。

它是这样的:

(SELECT * FROM table WHERE column = 34)
UNION
(SELECT * FROM table WHERE column2 = 45);
Run Code Online (Sandbox Code Playgroud)

然后你可以在最后添加一个 ORDER BY,如:

(SELECT * FROM table WHERE column = 34)
UNION
(SELECT * FROM table WHERE column2 = 45)
ORDER BY column;
Run Code Online (Sandbox Code Playgroud)