简体   繁体   English

如何将两个具有相同列的表组合在一起,并且每一行都有该表的标识?

[英]How to combine two tables with the same column and each row there is identity of the table?

How to combine two tables with the same column and each row there is identity of the table? 如何将两个具有相同列的表组合在一起,并且每一行都有该表的标识? And order by the column 并按栏排序

Here's the sample I want: 这是我想要的示例:

what's the sql query snytax 什么是SQL查询语法

SELECT Product_id,Product_name,Price,'table1' as table_identity 
    FROM `Table_1`
UNION 
SELECT Product_id,Product_name,Price,'table2' as table_identity 
    FROM `Table_2`
ORDER BY Price ASC

This will work if in both tables, the columns have the same data type, and if you make sure to select them in the same order. 如果两个表中的列都具有相同的数据类型,并且确保您以相同的顺序选择它们,那么这将起作用。

You shold be use "Union All" join between two tables and add additional column with table name to identity table. 您应该在两个表之间使用“ Union All”联接,并将具有表名的其他列添加到身份表。 you can also make VIEW of this query in SQL Server. 您还可以在SQL Server中对此查询进行查看。

select *, 'Table 1' as table_identity  from [table 1]
Union All
select *, 'Table 2' as table_identity from [table 2]
Order by Product_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM