MySQL:获取前一条记录的ID

时间:2012-03-02 16:20:19

标签: php mysql sql

我有一张桌子:

ID  NAME    ...n
1   JANE
2   SAM
3   PENNY
4   WATSON
5   ALISON
6   HANNA
7   BRIAN
..  ..
.   .

此表格不按字母顺序排序。我想做出这样的选择:

1)该表按字母顺序排列A..Z(ORDER BY NAME)

2)我想提供ID(或NAME)并获取前一行的ID(或NAME)。 例如 - >按字母顺序排列。我想提供BRIAN(7)并获得ALISON(5)

我正在使用PHP和MySQL。

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:2)

SELECT id, name
FROM names
WHERE name < 'BRIAN'
ORDER BY name DESC
LIMIT 1

答案 1 :(得分:1)

尝试:

select ID, name from
(select *
 from myTable
 where name < ?
 order by name desc) sq
group by ()

答案 2 :(得分:1)

Select * from table where id < (select id where condition order by condition) 
order by condition limit 1

答案 3 :(得分:1)

使用所需的ID填充@given_id,并确保您在NAME上有索引:

SELECT @target_id as prev_id
FROM names, (SELECT @prev_id:=-1, @target_id:=-1, @given_id:=7) as init
WHERE IF(ID=@given_id,
         GREATEST(@target_id:=@prev_id, @prev_id:=ID),
         LEAST(0, @prev_id:=ID))
ORDER BY NAME;

如果您需要获取id旁边的其他字段,请将查询放在子查询中,并与prev_id = id上的表进行连接。