好的,所以我被困在某事上,我需要你的幫助。這怎么能正常運行:
select salary from employees
where job_id = 'AD_PRES' and rownum <= 5
order by salary desc
這不是嗎?
select * from employees
where
salary in
(
select salary from employees
where job_id = 'AD_PRES' and rownum <= 5
order by salary desc
)
我得到的錯誤是: 00907. 00000 - "missing right parenthesis"
uj5u.com熱心網友回復:
在 SQL 中,一般情況下,表的排序是不確定的,不能保證一個順序。
您的查詢:
select salary
from employees
where job_id = 'AD_PRES'
and rownum <= 5
order by salary desc;
將以非確定性(隨機)順序從表中獲取行1然后它將應用該WHERE子句僅包含行,job_id = 'AD_PRES'并ROWNUM按照讀取的順序將偽列值分配給行,并在找到后停止5 行。之后,它將按照薪水的順序對前(隨機)5 行進行排序。
您想要的是ORDER BY在過濾之前應用該子句ROWNUM:
SELECT salary
FROM (
SELECT salary
FROM employees
WHERE job_id = 'AD_PRES'
ORDER BY salary DESC
)
WHERE rownum <= 5
從 Oracle 12 開始,有一個更簡單的語法:
SELECT salary
FROM employees
WHERE job_id = 'AD_PRES'
ORDER BY salary desc
FETCH FIRST 5 ROWS ONLY;
這怎么能正常運行……而這不行?
正如@OldProgrammer 所說,因為IN是一個集合操作,將順序應用于無序集合是沒有意義的,并且語法不允許ORDER BY在這種情況下使用子句。該"missing right parenthesis"錯誤是由于提高甲骨文的不期望ORDER BY子句中的IN串列,取而代之的是,確實希望子查詢與一個右括號關閉
您需要做的是使用不在ORDER BY子查詢最外層查詢中的查詢或使用新FETCH語法。
select *
from employees
where salary in (
SELECT salary
FROM (
SELECT salary
FROM employees
WHERE job_id = 'AD_PRES'
ORDER BY salary DESC
-- You can use `ORDER BY` in a nested sub-query
)
WHERE rownum <= 5
-- No ORDER BY clause in the outer-most sub-query of an IN expression
)
或者:
select *
from employees
where salary in (
SELECT salary
FROM employees
WHERE job_id = 'AD_PRES'
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY
)
db<>在這里擺弄
- 由于它的實作方式,它可能看起來是確定性(非隨機)順序,因為以一致的順序從資料檔案中讀取行。但是,這永遠無法保證,并且在某些情況下,行的順序會發生變化;特別是在并行系統上或當表啟用了行移動時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373075.html
