合并两列并对它们进行分组

时间:2013-07-12 11:07:49

标签: mysql sql group-by

例如我有这个:

命名

ID   | NAME
1    | Aiden
2    | Jackson
3    | Ethan

name_old

ID   | NAME
1    | Aiden
2    | Liam
3    | Mason
4    | Noah
5    | Ethan

我想得到:

结果

NAME
Aiden
Jackson
Ethan
Liam
Mason
Noah

我无法弄清楚查询会做什么工作。我猜想以某种方式合并而不是按结果分组?

4 个答案:

答案 0 :(得分:3)

UNION将从部分和合并常见结果中获取结果。

select NAME from name
UNION
select NAME from name_old;

SqlFiddle

答案 1 :(得分:1)

试试这个

declare @name table(id int identity(1,1),name varchar(50))
insert into @name select 'aiden'
insert into @name select 'jackson'
insert into @name select 'ethan'
insert into @name select 'stephen'

declare @name_old table(id int identity(1,1),name varchar(50))
insert into @name_old select 'aiden'
insert into @name_old select 'jackson'
insert into @name_old select 'ethan'
insert into @name_old select 'mason'
insert into @name_old select 'noah'
insert into @name_old select 'ethan'

select distinct t.name from
(
select name from @name
union
select name from @name_old
) as t

答案 2 :(得分:0)

使用右外连接

RIGHT JOIN关键字返回右表(table2)中的所有行,左表(table1)中的匹配行。当没有匹配时,结果在左侧为NULL。

SELECT NAME
 FROM name
 RIGHT JOIN name_old
 ON name.NAME=name_old.NAME;

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

答案 3 :(得分:0)

您需要的是UNION

SELECT NAME FROM NAME
UNION
SELECT NAME FROM NAME_OLD

请参阅this SQLFiddle