将 2 个 SQL SELECT 结果集合并为一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2317686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Joining 2 SQL SELECT result sets into one
提问by Vance
I've got 2 select statements, returning data like this:
我有 2 个选择语句,返回这样的数据:
Select 1
col_a col_b
Select 2
col_a col_c
If I do union, I get something like
如果我做工会,我会得到类似的东西
col_a col_b
And rows joined. What i need is getting it like this:
和行加入。我需要的是这样的:
col_a col_b col_c
Joined on data in col_a
加入数据 col_a
回答by Mark Byers
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
使用 JOIN 连接子查询并使用 ON 说明每个子查询中的行必须匹配的位置:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
如果 col_a 的某些值在 T1 中但不在 T2 中,则可以改用 LEFT OUTER JOIN。
回答by p2u
Use a FULL OUTER JOIN:
使用完全外连接:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
回答by H?vard S
SELECT table1.col_a, table1.col_b, table2.col_c
FROM table1
INNER JOIN table2 ON table1.col_a = table2.col_a