简体   繁体   中英

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

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. you can also make VIEW of this query in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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