我如何将两个表作为单个表格来查看或任何其他进程?

时间:2018-05-16 07:48:43

标签: mysql cakephp-2.0

我如何将两个表格作为单个表格,如视图或任何其他过程

表1  table1

表2 table2

result should be 结果应该是

2 个答案:

答案 0 :(得分:0)

您可以使用union all

select *, 'table1' as table_name from table1
union all
select *, 'table2' as table_name from table2

确保两个表都有相同的号码。列,如果没有,则指定所需的列名称,例如选择col1,col2 ...

如果你想创建一个新表,那么

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

CREATE TABLE ... SELECT Syntax

答案 1 :(得分:0)

(
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
)