我正在尝试使Order By子句可用于查询,但它似乎无法正常运行。我的目标如下
我遇到的问题是ORDER BY
子句似乎不起作用。我正在测试的用户的文档中doc_def_id
为“ 55”,mailed_date
为06/22/2018,而文档中的doc_def_id
为“ 57”,并且mailed_date
为07/08/2018。据我所知,它应该给我{57}的doc_def_id
,因为它有较新的邮件日期,但是它似乎忽略了ORDER BY
子句,并给了我第一个结果(好像没有) ORDER BY
子句)。
代码:
SELECT
ual.user_id,
ual.account_id,
dr.mailed_date,
dr.doc_def_id
FROM doc_request dr
JOIN user_account_link ual
ON dr.account_id = ual.account_id
WHERE
ual.user_id = '123456'
AND dr.mailed_date = (
SELECT Max(dr.mailed_date)
FROM doc_request
WHERE ual.user_id = '123456'
AND dr.doc_def_id IN ('55','57')
)
AND ROWNUM <= 1
ORDER BY dr.mailed_date DESC;
答案 0 :(得分:1)
最新的Oracle版本支持ANSI SQL FETCH FIRST
子句:
SELECT ual.user_id, ual.account_id, dr.mailed_date, dr.doc_def_id
FROM doc_request dr
join user_account_link ual ON dr.account_id = ual.account_id
WHERE ual.user_id = '123456'
AND dr.doc_def_id IN ('55','57')
ORDER BY dr.mailed_date DESC
FETCH FIRST 1 ROW ONLY
答案 1 :(得分:0)
应该在外部查询中使用ROWNUM以获得确切的最大日期。
select * from
(SELECT ual.user_id, ual.account_id, dr.mailed_date, dr.doc_def_id
FROM doc_request dr
join user_account_link ual ON dr.account_id = ual.account_id
WHERE ual.user_id = '123456'
AND dr.mailed_date = (SELECT Max(dr.mailed_date)
FROM doc_request
WHERE ual.user_id = '123456'
AND dr.doc_def_id IN ('55','57'))
ORDER BY dr.mailed_date DESC)
WHERE ROWNUM=1;