考虑一个名为user
的表有两个字段的数据库:
"id" (type: INTEGER, PRIMARY KEY) "name" (type: VARCHAR(32))
编写标准SQL查询,从id
表中检索user
的第二高值。返回的值应使用列名id
来表示。
哪个是标准SQL?
select id from user order by id desc limit 1,1;
select user.id as id from user order by user.id desc limit 1,1;
如果他们两个都错了,然后正确答案?
答案 0 :(得分:3)
据我所知,TOP
和LIMIT
都不是由SQL标准定义的(至少我找不到它)。
所以唯一纯粹的标准解决方案是使用窗口函数:
select *
from (
select id,
row_number() over (order by id desc) as rn
from "user"
) as t
where rn = 2;
答案 1 :(得分:1)
SELECT MAX( id) FROM user where id !=( SELECT max (id) FROM user )
答案 2 :(得分:1)
select
secondhighest.id
from
"user" highest
left join "user" biggerthanhighest on
biggerthanhighest.id > highest.id
left join "user" secondhighest on
highest.id > secondhighest.id
left join "user" biggerthansecondhighest on
biggerthansecondhighest.id > secondhighest.id and
biggerthansecondhighest.id < highest.id
where
biggerthanhighest.id is null and
biggerthansecondhighest.id is null
将避免顶部和子查询。在真正大的桌子上可能会相当快?
答案 3 :(得分:0)
SELECT TOP 1 id
FROM (
SELECT DISTINCT TOP 2 id
FROM user
ORDER BY id DESC) a
ORDER BY id
我认为这是非常标准的。
答案 4 :(得分:0)
SELECT TOP 1 "id" FROM (SELECT TOP 2 "id" FROM "user" ORDER BY "id" DESC) AS "wt" ORDER BY "id"