【发布时间】:2009-10-05 14:56:15
【问题描述】:
假设出于某种原因,我在两个单独的表中分别有员工,员工 1 和员工 2
我只想把它们加在一起,就好像它们叠在一起一样。
类似:
select all from employee1 and employee2 where name = bubba
我知道我在概括,这最终将在 postgres 中,所以如果有任何细节我应该注意谢谢
【问题讨论】:
-
西部最快的枪 - 观察。
假设出于某种原因,我在两个单独的表中分别有员工,员工 1 和员工 2
我只想把它们加在一起,就好像它们叠在一起一样。
类似:
select all from employee1 and employee2 where name = bubba
我知道我在概括,这最终将在 postgres 中,所以如果有任何细节我应该注意谢谢
【问题讨论】:
SELECT field1, field2, field2 FROM tableA WHERE field1='x'
UNION
SELECT field1, field2, field2 FROM tableB WHERE field1='x'
如果您想要每条记录,甚至重复,请使用UNION ALL。
【讨论】:
你只想做一个联合
select * from Employee1 where name = 'bubba'
union
select * from Employee2 where name = 'bubba'
【讨论】:
您将需要使用 UNION 关键字
select * from employee1 where name = 'bubba'
union
select * from employee2 where name = 'bubba'
【讨论】:
在大多数数据库中,您所请求的内容称为UNION,并如下所示:
select all from employee1 where name = bubba
UNION
select all from employee2 where name = bubba
这来自Relational Algebra's "union" operator,它的原语之一。
请注意,UNION 遵循集合并集,即对于 E1 和 E2 表之间重复的任何行,它只会选择该行的 ONE 副本。如果要选择所有副本,请使用“UNION ALL”运算符。
【讨论】:
我想你指的是UNION 操作。
【讨论】:
如果表具有相同的架构则
SELECT * FROM employee1 UNION SELECT * FROM employee2
两个表的列数必须相同,并且列的类型必须相似。
【讨论】:
我猜是工会
从员工 1 中选择 *,其中 name = 'bubba'
联合
select * from employee2 where name = 'bubba'
如果您还想要重复,请使用 union all。
【讨论】:
你想要的是一个“联合所有”:
select * from employee1
union all
select * from employee2;
列类型和顺序必须匹配,否则您需要在选择列表中提供列列表而不是“*”。可以将“where”子句添加到任一“select”语句或两个“select”语句中。
没有“all”,两个查询之间的任何重复行都将折叠成一行。如果这是您想要的,只需删除“全部”即可。
【讨论】:
正如其他人提到的,你想要UNION。但是,如果您真的想要堆叠的结果,您应该使用UNION ALL。 UNION 将删除欺骗,UNION ALL 并包含它们。见http://www.postgresql.org/docs/8.2/interactive/queries-union.html
【讨论】:
不管怎样,union all 执行起来更快,因为它不需要排序来消除两组中的重复项。
【讨论】: