[英]SQL selecting from 3 tables with the same column names
我有三个具有以下结构的表:
sequence
cli
datetime
company
该表是orders_broadband
orders_lines
和orders_porting
我想显示同一结果集中所有三个表的结果。
我试过运行查询:
SELECT orders_broadband.*, orders_lines.*, orders_porting.* from orders_broadband, orders_lines, orders_porting
但我不认为查询正确
你可以这样做:
select sequence, cli, datetime, company from orders_broadband
union all
select sequence, cli, datetime, company from orders_lines
union all
select sequence, cli, datetime, company from orders_porting
这将合并所有3个表中的数据。
通过显式添加列名进行编辑(类似于注释部分中提到的xQbert)
显示表名
select sequence, cli, datetime, company, 'Tablename1' as tbl from orders_broadband where status = 'New'
UNION ALL
select sequence, cli, datetime, company, 'Tablename2' as tbl from orders_lines where status = 'New'
UNION ALL
select sequence, cli, datetime, company, 'Tablename3' as tbl from orders_porting where status = 'New'
将“ Tablename1”和其他名称更改为您认为合适的名称。
如果要从orders_broadband添加其他列怎么办?
select '' as telephone_number, sequence, cli, datetime, company, 'Tablename1' as tbl from orders_broadband where status = 'New'
UNION ALL
select '' as telephone_number, sequence, cli, datetime, company, 'Tablename2' as tbl from orders_lines where status = 'New'
UNION ALL
select telephone_number, sequence, cli, datetime, company, 'Tablename3' as tbl from orders_porting where status = 'New'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.