我有这样的表MY_TABLE,该表存储许多表中更改的数据(更新跟踪)。因此,每当其他表进行一些更新时,我都会使用基本表上的AFTER UPDATE TRIGGER
将新数据存储在MY_TABLE中。
ID RECORD_DESC EMP_ID FIRST_NAME LAST_NAME GENDER SALARY 1 EMP 5 ABC XYZ 2 EMP 5 M 3 EMP 5 XYZ-NEW F 4 SAL 5 1000 5 EMP 5 M 6 SAL 5 ABC-NEW 750
现在我要查询MY_TABLE以从所有列中获取具有最新更改的员工数据,结果应类似于此行:
EMP_ID FIRST_NAME LAST_NAME GENDER SALARY 5 ABC-NEW XYZ-NEW M 750
我到目前为止所做的是,获取每一列的MAX(ID),并从该ID中再次查询表以获取该ID的列值。
但是问题是此查询将在数据库上承受相当大的负载,因为我有25个这样的列,并且表会随着时间而变大。
所以,有人可以建议我更好的方法来编写下面的查询:
SELECT (SELECT FIRST_NAME FROM MY_TABLE WHERE ID = T2.FIRST_NAME_PK) AS FIRST_NAME
, (SELECT LAST_NAME FROM MY_TABLE WHERE ID = T2.LAST_NAME_PK ) AS LAST_NAME
, (SELECT GENDER FROM MY_TABLE WHERE ID = T2.GENDER_PK ) AS GENDER
, (SELECT SALARY FROM MY_TABLE WHERE ID = T2.SALARY_PK ) AS SALARY
FROM (SELECT (SELECT MAX(ID) FROM MY_TABLE WHERE EMP_ID = T1.EMP_ID AND FIRST_NAME IS NOT NULL) FIRST_NAME_PK -- ID = 6
, (SELECT MAX(ID) FROM MY_TABLE WHERE EMP_ID = T1.EMP_ID AND LAST_NAME IS NOT NULL) LAST_NAME_PK -- ID = 3
, (SELECT MAX(ID) FROM MY_TABLE WHERE EMP_ID = T1.EMP_ID AND GENDER IS NOT NULL) GENDER_PK -- ID = 5
, (SELECT MAX(ID) FROM MY_TABLE WHERE EMP_ID = T1.EMP_ID AND SALARY IS NOT NULL) SALARY_PK -- ID = 6
FROM (SELECT DISTINCT EMP_ID
FROM MY_TABLE
) T1
) T2;
我有这样的表MY_TABLE,该表存储许多表中更改的数据(更新跟踪)。因此,每当其他表进行某些更新时,我都会在...