Reputation: 2293
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.
function rand()
{
$sth = $this->db->prepare("SELECT rows FROM table ORDER BY id LIMIT 1");
$sth->execute();
}
+--------------+
| id | name |
+--------------+
| 1 | Jon |
| 2 | Sarah |
| 3 | Stevie |
| 4 | Stew |
| 5 | Dave |
| 6 | Kar |
| 7 | Stevo |
| 8 | Blake |
+----+---------+
+----+ | id | +----+ | | | | | | | | | | | | | | | || |
Upvotes: 1
Views: 99
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
Reputation: 1579
Have you tried this:
SELECT name
FROM users
ORDER BY RAND()
LIMIT 3
http://davidwalsh.name/mysql-random
Upvotes: 0