Select previous row mysql?

后端 未结 5 1178
猫巷女王i
猫巷女王i 2021-01-27 10:11

If I have a mysql table which had primary ids and another field called gameScore can I do something along the lines of...

SELECT gameScore FROM table1 WHERE id =         


        
相关标签:
5条回答
  • 2021-01-27 10:25

    Something like this -

    SELECT t1.* FROM table1 t1
      JOIN (
        SELECT id, MAX(gameScore) gameScore FROM table1
          WHERE id = 100 AND gameScore < 50 ORDER BY gameScore
      ) t2
        On t1.id = t2.id AND t1.gameScore = t2.gameScore
    

    To find previous record we need to select exact current record, in example it is a record with id = 100 and gameScore = 50.

    0 讨论(0)
  • 2021-01-27 10:30

    looks funny - but maybe this is what you're after.

    select max( gameScore )
    from table1
    where id = 100
    and gameScore < ( select max( gameScore ) from table1 where id = 100 )
    
    0 讨论(0)
  • 2021-01-27 10:30

    check out the Lag feature mentioned on this site http://explainextended.com/2009/03/10/analytic-functions-first_value-last_value-lead-lag/

    0 讨论(0)
  • 2021-01-27 10:36

    You're looking for the second lowest score, right? Like Craig mentioned, limit sounds like the right way to go:

    SELECT 
      gameScore 
    FROM 
      table1 
    WHERE 
      id = 100 
    ORDER BY 
      gameScore ASC 
    limit 1,1
    
    0 讨论(0)
  • 2021-01-27 10:48

    I would suggest doing a union instead of the AND (besides, you need to add LIMIT 1 so you do not get ALL rows under 100)

    0 讨论(0)
提交回复
热议问题