从具有相同列的多个表中获取所有记录

时间:2017-04-20 08:28:20

标签: sql

我的数据库中有3个表,这3个表有公共列。第1列为Name,第2列为printed,第3列为location

我要做的是从这3张表中获取所有记录

where printed = "NO" and location = "Submitted" 

这样的东西
select * 
from table1, table2, table3 
where printed = "NO" and Location = "Submitted"

这可用吗?

2 个答案:

答案 0 :(得分:1)

您可以使用union来达到目标​​。 Union附加单独查询的结果集:

select name, printed, location from table1 where printed = "NO" and Location = "Submitted"
union
select name, printed, location from table2 where printed = "NO" and Location = "Submitted"
union
select name, printed, location from table3 where printed = "NO" and Location = "Submitted"

如果您想知道特定记录来自哪个表,请为每个查询添加一个常量字段:

select name, printed, location, "table1" as table_name from table1 where printed = "NO" and Location = "Submitted"
...

答案 1 :(得分:1)

如果所有3个表具有相同的结构:

select t1.*
from table1 t1
where printed = 'NO' and Location = 'Submitted'
union 
select t2.*
from table2 t2
where printed = 'NO' and Location = 'Submitted'
union 
select t3.*
from table3 t3
where printed = 'NO' and Location = 'Submitted'

如果结构不同(即每个表中的不同列):

select t1.somecolumn, t1.someothercolumn, t1.etc
from table1 t1
where printed = 'NO' and Location = 'Submitted'
union 
select t2.somecolumn, t2.someothercolumn, t2.etc
from table2 t2
where printed = 'NO' and Location = 'Submitted'
union 
select t3.somecolumn, t3.someothercolumn, t3.etc
from table3 t3
where printed = 'NO' and Location = 'Submitted'

union必须返回相同数据类型的列,并按所选顺序返回它们,由第一个选择定义...如果您有重复项,UNION将删除它们。如果您想保留重复项,请改用UNION ALL