我是Oracle SQL的新手,所以如果我的问题实际上有一个相对学生化的答案,请原谅我。
因此,我有两个表,应用程序和应用程序历史,定义如下。
Apps Apps_history
ID ID
Other APP_ID
DATE_MODIFIED STATUS
DATE_MODIFIED
Apps_history有app_id,这是Apps中主键id的外键,Apps中的记录会经常更新,并且Apps_history会跟踪这一点。我希望在创建应用程序中的ID时显示一个新列,这可以从状态等于"initialized"时在apps_History中修改的列date_modified派生。
目前这就是我的
select *, t.date_modified as create_date
(select app_history.date_modified
from apps
inner join app_history on
apps.id=app_history.app_id where
status='initialized') T
from apps;
但我遇到了一些错误,任何帮助我朝着正确的方向前进的人都非常感激,
感谢
有多种方法可以实现这一点。您似乎已经开始了相关子查询的道路,所以继续进行:
select a.*,
(select ah.date_modified
from app_history ah
where a.id = ah.app_id and ah.status = 'initialized')
) as created_date
from apps a;
为了提高性能,我建议使用app_history(app_id, status, date_modified)
索引。
您的子查询不相关。您可以使用@Gordon建议的关联查询来解决此问题。此外,如果您从相关的子查询中获取多行,但这是可以修复的,则会引发错误。
我会使用左自联接。
select a.*,
t.date_modified as create_date
from apps a
left join apps t on a.id = t.app_id
and t.status = 'initialized';