将两个 table 与一个 table _name 列合并
Union two tables with a table _name column
我想合并两个表(Student1,Student2)。
1 - 学生 1
| student_code | name |
--------------------------
| 1 | katia |
| 2 | roger |
| 3 | ken |
2 - 学生 2
| student_code | name |
--------------------------
| 3 | katia |
| 4 | roger |
| 5 | ken |
那么我想要这样的结果。
结果
|table_name| student_code | name |
-------------------------------------
|Student1 | 1 | katia |
|Student1 | 2 | roger |
|Student1 | 3 | ken |
|Student2 | 3 | katia |
|Student2 | 4 | roger |
|Student2 | 5 | ken |
我只想使用 ANSI sql。
select 'Student1' AS table_name,student_code,name from student1
union
select 'Student2' AS table_name,student_code,name from student2
我假设你知道UNION
和UNION ALL
之间的区别,union
带来独特的记录,它和UNION PERFORMED ON SETS
一样,而union all
会带来也有重复的行。
在您的情况下,由于第一列区分行,因此即使合并也会带来重复。
你可以使用
SELECT 'Student1' AS table_name, student_code, name FROM Student1
UNION ALL
SELECT 'Student2' AS table_name, student_code, name FROM Student2
Use UNION ALL statement :
SELECT 'Student1' as table_name, student_code, name FROM Student1
UNION ALL
SELECT 'Student2' as table_name, student_code, name FROM Student2
我想合并两个表(Student1,Student2)。
1 - 学生 1
| student_code | name |
--------------------------
| 1 | katia |
| 2 | roger |
| 3 | ken |
2 - 学生 2
| student_code | name |
--------------------------
| 3 | katia |
| 4 | roger |
| 5 | ken |
那么我想要这样的结果。
结果
|table_name| student_code | name |
-------------------------------------
|Student1 | 1 | katia |
|Student1 | 2 | roger |
|Student1 | 3 | ken |
|Student2 | 3 | katia |
|Student2 | 4 | roger |
|Student2 | 5 | ken |
我只想使用 ANSI sql。
select 'Student1' AS table_name,student_code,name from student1
union
select 'Student2' AS table_name,student_code,name from student2
我假设你知道UNION
和UNION ALL
之间的区别,union
带来独特的记录,它和UNION PERFORMED ON SETS
一样,而union all
会带来也有重复的行。
在您的情况下,由于第一列区分行,因此即使合并也会带来重复。
你可以使用
SELECT 'Student1' AS table_name, student_code, name FROM Student1
UNION ALL
SELECT 'Student2' AS table_name, student_code, name FROM Student2
Use UNION ALL statement :
SELECT 'Student1' as table_name, student_code, name FROM Student1
UNION ALL
SELECT 'Student2' as table_name, student_code, name FROM Student2