问题
Following is the sql query (oracle) that I use to get the last record of the returning result of the select query. Is this the optimum way?
SELECT HAZMAT_PLACARD_NOTATION
INTO v_pcn
FROM HAZMAT_CLASS_IRF
WHERE HAZMAT_CD = p_stcc_cd and ROWID = (SELECT MAX(ROWID) FROM HAZMAT_CLASS_IRF WHERE HAZMAT_CD = p_stcc_cd);
Following is an example result set of the select query where HAZMAT_CD = 4920111 But the last row with the HAZMAT_PLAYCARD_NOTATION value SPONTANEOUSLY COMBUSTIBLE should be retrieved. That's the objective
回答1:
Get last record of result set
There are many ways:
Oracle Pre-12c
version:
- ROWNUM in sub-query and ORDER BY in outer query
- Analytic function
Oracle 12c
version:
- Top-n Row Limiting feature
Using ROWNUM
SELECT HAZMAT_PLACARD_NOTATION
INTO v_pcn
FROM
(SELECT HAZMAT_PLACARD_NOTATION,
ROWNUM rn
FROM HAZMAT_CLASS_IRF
WHERE HAZMAT_CD = p_stcc_cd
ORDER BY <sort_column> DESC
)
WHERE rn =1;
Using Top-n Row Limiting feature
SELECT HAZMAT_PLACARD_NOTATION
INTO v_pcn
FROM HAZMAT_CLASS_IRF
WHERE HAZMAT_CD = p_stcc_cd
ORDER BY <sort_column> DESC
FETCH FIRST 1 ROW ONLY;
Have a look at this answer for examples and detailed explanation.
回答2:
In mysql ,you can try this.
SELECT *
FROM `table`
ORDER BY id DESC
LIMIT 0 , 1
回答3:
In older sqlserver versions (<2014) you don't have the ROW_NUMBER at your disposal.
But you can easily use Top 1 and order by desc
select top 1 * from tblc2scdocumentcodes where C2scDocumentCode like '%.14.%' and C2scDocumentCode like '%DTP.SO.%' order by C2scDocumentCode desc
The query returns a resultset. The order of this resultset is 'reversed' and then limited to 1 record
回答4:
select * from
(
select * from table order by id desc
)
where rownum = 1
来源:https://stackoverflow.com/questions/31421549/get-last-record-of-result-set