0

考虑一个具有一个表的数据库,称为user具有两个字段:

“id”(类型:整数,主键)
“名称”(类型:VARCHAR(32))

id编写一个标准 SQL 查询,从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;

如果他们都错了,然后正确答案?

4

5 回答 5

3

据我所知,SQL标准既没有TOP也没有LIMIT定义(至少我找不到)。

所以唯一的纯标准解决方案是使用窗口函数:

select *
from (
   select id, 
          row_number() over (order by id desc) as rn
   from "user"
) as t 
where rn = 2;
于 2013-06-27T06:42:19.947 回答
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

将避免顶部和子查询。在非常大的桌子上可能相当快?

于 2013-06-27T06:22:56.957 回答
1
SELECT MAX( id) FROM user where id !=( SELECT max (id) FROM user ) 
于 2013-06-27T06:05:55.830 回答
0
SELECT TOP 1 id
FROM (
SELECT DISTINCT TOP 2 id
FROM user
ORDER BY id DESC) a
ORDER BY id

这也是我认为的标准。

于 2013-06-27T03:38:30.743 回答
0
SELECT TOP 1 "id" FROM (SELECT TOP 2 "id" FROM "user" ORDER BY "id" DESC) AS "wt" ORDER BY "id"
于 2013-06-27T06:34:30.877 回答