8

我想用三个表的联合创建视图。但在结果查询中,我想要一个额外的列,如“tableId”。

我的代码就像

CREATE OR REPLACE VIEW DETAILS
AS SELECT 
* FROM
(
SELECT 
    T1.ID,
    T1.AMOUNT,
    T1.STATUS,
    T1.ADDEDBY,
    T1.ADDEDON
FROM Table1 T1
UNION ALL
SELECT 
    T2.ID,
    T2.AMOUNT,
    T2.STATUS,
    T2.ADDEDBY,
    T2.ADDEDON
FROM Table2 T2
UNION ALL
SELECT
    T3.ID,
    T3.BILLAMOUNT,
    T3.STATUS,
    T3.ADDEDBY,
    T3.ADDEDON  
FROM Table3 T3
);

这给了我所需的三个表的联合。但是如何在结果输出中获取表 ID 列?此列在三个表中的任何一个中都不存在。

4

6 回答 6

13

听起来您只想在SELECT列表中添加一个额外的硬编码值

CREATE OR REPLACE VIEW DETAILS
AS SELECT 
* FROM
(
SELECT 
    T1.ID,
    T1.AMOUNT,
    T1.STATUS,
    T1.ADDEDBY,
    T1.ADDEDON,
    'T1' tableID
FROM Table1 T1
UNION ALL
SELECT 
    T2.ID,
    T2.AMOUNT,
    T2.STATUS,
    T2.ADDEDBY,
    T2.ADDEDON,
    'T2' tableID
FROM Table2 T2
UNION ALL
SELECT
    T3.ID,
    T3.BILLAMOUNT,
    T3.STATUS,
    T3.ADDEDBY,
    T3.ADDEDON,
    'T3' tableID  
FROM Table3 T3
);
于 2012-07-23T08:02:17.427 回答
6
CREATE OR REPLACE VIEW DETAILS
AS SELECT 
* FROM
(
SELECT 
    T1.ID,
    T1.AMOUNT,
    T1.STATUS,
    T1.ADDEDBY,
    T1.ADDEDON,
    'Table1' as tableid
FROM Table1 T1
UNION ALL
SELECT 
    T2.ID,
    T2.AMOUNT,
    T2.STATUS,
    T2.ADDEDBY,
    T2.ADDEDON,
    'Table2' as tableid
FROM Table2 T2
UNION ALL
SELECT
    T3.ID,
    T3.BILLAMOUNT as AMOUNT,
    T3.STATUS,
    T3.ADDEDBY,
    T3.ADDEDON,    
    'Table3' as tableid
FROM Table3 T3
);
于 2012-07-23T08:02:21.033 回答
0

列的数据来自哪里?

如果您正在寻找什么,您可以添加完全静态的数据:

select 'hello there' from Table1;

create view v1 as select 123 as table_id, a_column from Table2;

select 'Table1' as table_id, a_column from Table1
union all
select 'Table2', a_column from Table2
于 2012-07-23T08:02:15.207 回答
0

对此有更好的解决方案;

NULL AS COLUMN_NAME是一个标识符。

CREATE VIEW MY_VIEW
    AS
        (SELECT A.*,NULL AS COLUMN1,NULL AS COLUMN2,NULL AS COLUMN3
            FROM MY_TABLE A)
于 2015-12-16T07:38:55.450 回答
0

我做了同样的事情。

  1. 打开phpmyadmin。
  2. 选择数据库。
  3. 点击sql菜单
  4. 运行以下命令 -

CREATE VIEW table_name AS SELECT tableA.id, tableA.name, tableA.duty_hours, tableA.rate, NULL AS 'additional_field1',NULL AS 'additional_field2', NULL AS 'additional_field3', tableB.name, tableB.email, tableB.charge, NULL AS 'additional_field4' FROM tableA join tableB using (id) ;

这对我有用。

于 2017-08-30T11:11:18.743 回答
-2
create or replace view view1(col1,col2,col3) as select col1,col2,nul 
于 2015-10-27T10:13:08.113 回答