I have a table:
ID NAME ...n
1 JANE
2 SAM
3 PENNY
4 WATSON
5 ALISON
6 HANNA
7 BRIAN
.. ..
. .
This table is not ordered alphabetically. I want to make such a selection that:
1) The table gets alphabetically ordered A..Z (ORDER BY NAME)
2) I want to supply the ID (or NAME) and get the ID (or NAME) of the preceding row. eg -> Once alphabetically ordered. I want to supply BRIAN (7) and get ALISON (5)
I am using PHP and MySQL.
How can I achieve this?
SELECT id, name
FROM names
WHERE name < 'BRIAN'
ORDER BY name DESC
LIMIT 1
Try:
select ID, name from
(select *
from myTable
where name < ?
order by name desc) sq
group by ()
Select * from table where id < (select id where condition order by condition)
order by condition limit 1
Populate the @given_id
with the required id and make sure you have an index on 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;
If you need to fetch other fields beside id, put the query in a subquery and make a join with the table on prev_id = id.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.