我想用三个表的联合创建视图。但在结果查询中,我想要一个额外的列,如'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列?此列不存在于三个表中的任何一个中。
答案 0 :(得分:12)
听起来您只想在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
);
答案 1 :(得分:5)
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
);
答案 2 :(得分: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
答案 3 :(得分: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)
答案 4 :(得分:0)
我为此做了什么。
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) ;
这对我有用。
答案 5 :(得分:-2)
create or replace view view1(col1,col2,col3) as select col1,col2,nul