如何将两个表作为一个类似表的视图或任何其他进程来排列?

exdqitrt  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(245)

如何将两个表作为类似于单个表的视图或任何其他过程来排列
表1

表2


结果应该是

nwsw7zdq

nwsw7zdq1#

你可以用 union all ```
select *, 'table1' as table_name from table1
union all
select *, 'table2' as table_name from table2

确保两个表的列数相同,如果没有,则指定所需的列名,如select col1、col2。。。
如果您想创建一个新表,那么

create table new_table
select *, 'table1' as table_name from table1
union all
select *, 'table2' as table_name from table2

创建表。。。选择语法
b1payxdu

b1payxdu2#

(
SELECT
    `a`.`id` AS `id`,
    `a`.`name` AS `name`,
    'table1' AS `TABLE_NAME`
FROM
   `table1` `a`
ORDER BY
    `a`.`role`
LIMIT 5
)
UNION
(
SELECT
    `b`.`id` AS `id`,
    `b`.`student_name` AS `student_name`,
    'tavle2' AS `TABLE_NAME`
FROM
    `table2` `b`
ORDER BY
    `b`.`student_role`
LIMIT 5
)

相关问题