MySql randomize the last 10 rows

后端 未结 2 1646
面向向阳花
面向向阳花 2021-01-19 03:33

I need help on how to randomize the last 10 rows of MySql records.

$mysqld = mysql_query(select * from table where amount > amount2 and code = \'$code\' o         


        
相关标签:
2条回答
  • 2021-01-19 04:07

    Assuming that time is the time when record was inserted, this will get you the latest 10 rows from the table:

    SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code'
      ORDER BY `time` DESC LIMIT 10
    

    Now, you can use the result as a temporary table, sort it randomly (as it's only 10 rows) and return one row:

    SELECT * FROM (
      SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code'
        ORDER BY `time` DESC LIMIT 10
    ) AS temptable 
    ORDER BY RAND()
    LIMIT 1
    
    0 讨论(0)
  • 2021-01-19 04:18

    Try....

    SELECT * FROM (SELECT * FROM yerTable ORDER BY id DESC LIMIT 10) AS tmp ORDER BY RAND() LIMIT 1
    

    Obviously replace id with any other distinct column if preferred.

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