iBrazilian2
iBrazilian2

Reputation: 2293

How to select RAND() between 1-n

I'd like to use RAND() in a query to be able to do the following:

ODER BY id DESC and allow RAND() to choose between last 3 inserted rows in the table. 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.

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 | +----+ | | | | | | | | | | | | | | | || |

Upvotes: 1

Views: 99

Answers (2)

fthiella
fthiella

Reputation: 49069

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

Upvotes: 1

magicianiam
magicianiam

Reputation: 1579

Have you tried this:

SELECT name
FROM users
ORDER BY RAND()
LIMIT 3

http://davidwalsh.name/mysql-random

Upvotes: 0

Related Questions