更新时无效的标识符(Oracle)

时间:2015-10-13 16:48:40

标签: sql oracle ora-00904

我尝试执行以下命令:

UPDATE DB_TEST.STOCK_ITEMS
   SET STATUS = (SELECT *
                   FROM (SELECT STOCK_ITEM_STATUS
                           FROM DB_TEST.STOCK_ITEMS_HISTORY
                          WHERE STOCK_ITEM_ID = DB_TEST.STOCK_ITEMS.ID
                          ORDER BY CHANGED_ON DESC, ID DESC)
                  WHERE ROWNUM <= 1)
 WHERE EXISTS (SELECT *
                 FROM DB_TEST.STOCK_ITEMS_HISTORY
                WHERE STOCK_ITEM_ID = DB_TEST.STOCK_ITEMS.ID);

但我收到错误:

SQL-Error: ORA-00904: "DB_TEST"."STOCK_ITEMS"."ID": invalid identifier

我查了Oracle错误,但我得到的是我认为使用了错误或缺少的列名,但DB_TEST.STOCK_ITEMS.ID字段肯定存在。

还有哪些其他原因会导致此错误?

1 个答案:

答案 0 :(得分:2)

Oracle将表的范围限制为一个子查询级别。这是一种使用keep解决问题的方法:

UPDATE DB_TEST.STOCK_ITEMS
  SET STATUS = (SELECT MAX(STOCK_ITEM_STATUS) KEEP (DENSE_RANK FIRST ORDER BY CHANGED_ON DESC, ID DESC)
                FROM DB_TEST.STOCK_ITEMS_HISTORY
                WHERE STOCK_ITEM_ID = DB_TEST.STOCK_ITEMS.ID
               )
  WHERE EXISTS (SELECT 1
                FROM DB_TEST.STOCK_ITEMS_HISTORY
                WHERE STOCK_ITEM_ID = DB_TEST.STOCK_ITEMS.ID
               );