简体   繁体   English

如何在1-n之间选择RAND()

[英]How to select RAND() between 1-n

I'd like to use RAND() in a query to be able to do the following: 我想在查询中使用RAND()来执行以下操作:

ODER BY id DESC and allow RAND() to choose between last 3 inserted rows in the table. ODER BY id DESC并允许RAND()在表中最后插入的3行之间进行选择。 On the front-end when page is refreshed function rand will choose between 5 - 8 (on the table example) and show any data between those numbers. 在刷新页面的前端,功能rand将在5-8之间选择(在表格示例中),并显示这些数字之间的任何数据。

Query Example 查询范例

function rand()
{
    $sth = $this->db->prepare("SELECT rows FROM table ORDER BY id LIMIT 1");
    $sth->execute();

}

Table Example 表例

+--------------+
| id |   name  |
+--------------+
|  1 |    Jon  |
|  2 |  Sarah  |
|  3 | Stevie  |
|  4 |   Stew  |
|  5 |   Dave  |
|  6 |    Kar  |
|  7 |  Stevo  |
|  8 |  Blake  |
+----+---------+

EDIT 编辑

+----+ | + ---- + | id | id | +----+ | + ---- + | | | | | | | | | | | | | | | | | | | | | | | | | | | | | || || | |

If I understand your question correctly, I think you need this: 如果我正确理解了您的问题,我认为您需要这样做:

SELECT id, name
FROM
  (SELECT id, name FROM table ORDER BY id DESC LIMIT 3) s
ORDER BY rand()
LIMIT 1

Have you tried this: 您是否尝试过:

SELECT name
FROM users
ORDER BY RAND()
LIMIT 3

http://davidwalsh.name/mysql-random http://davidwalsh.name/mysql-random

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM