我有三个具有以下结构的表:
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'
关于mysql - SQL 从 3 个具有相同列名的表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011611/