I have a table record like below:-
my_table
id | rating | description
1 | 0.0 | bed
2 | 1.0 | good
3 | 0.0 | bed
4 | 1.0 | good
5 | 0.0 | bed
6 | 0.0 | bed
7 | 0.0 | bed
Now I shorted this table by rating and I got following result. (Query : SELECT * FROM my_table ORDER BY rating DESC)
Result table
id | rating | description
2 | 1.0 | good
4 | 1.0 | good
1 | 0.0 | bed
==> 3 | 0.0 | bed
5 | 0.0 | bed
6 | 0.0 | bed
7 | 0.0 | bed
Now I want previous record of id = 3.
expected result
id | rating | description
1 | 0.0 | bed
How can I achieve it. within single mysql query? Please help me.
用这个:
SELECT * FROM my_table ORDER BY rating DESC LIMIT 2,1
Try this
SELECT prev.id, rating, description
FROM my_table current
JOIN my_table prev
ON (prev.rating < current.rating)
OR (prev.rating = current.rating
AND (prev.description < current.description
OR (prev.description = current.description AND prev.id < current.id)))
WHERE current.id = @currentId
ORDER BY prev.rating desc, prev.description desc, prev.id desc
LIMIT 1
Try this for a quick solution:
SELECT * FROM my_table WHERE rating='0.0' and id<'3' ORDER BY id DESC LIMIT 1
This will select the row with the next lowest ID than the one specified that has a rating of 0.0. This will work without sorting BUT will not retrieve any rows that have a rating of 1.0, even if they would be the next line.
try this:
select * from my_table
where rating<(select max(rating) from my_table)
and
id<3
limit 1;
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.