2017-04-20 150 views
-1

我在我的数据库中有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" 

事情是这样可以让所有的记录?

+0

这可能与'union' – Shadow

+0

不能是MySQL和SQL服务器,它们是不同的产品 – JohnHC

+2

首先找出你正在使用的RDBMS(也许JohnHC已经为你弄明白了这一点)。然后参见http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查询 – Strawberry

回答

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 ALL

+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" 
... 
+0

小心报价,我几乎错过了自己 – JohnHC

+0

@JohnHC MySQL和MS SQL的双引号工作 – Shadow

+0

那么,每一天都是一个学校的日子 – JohnHC

相关问题