SQL select 3 random rows non-recurring in the last query
Considering my first query is selecting 5 last rows from the table named table1
like that:
SELECT * FROM table1 ORDER BY id DESC LIMIT 5
How can I manage my second query to get any 3 rand开发者_开发百科om rows, excluding the last 5 (so there is no way that I'd get any of the 5 rows from the first query)?
I thought about limit, but I had no luck constructing the query.
Meanwhile, I insert the id's from the first query into an array, and checking them against the random ones. But I wonder if there is an easier way to accomplish that (maybe pure SQL)?
SELECT t.* FROM table1 t, (
SELECT id FROM table1 ORDER BY id DESC LIMIT 5,1
) as x
WHERE t.id <= x.id
ORDER BY RAND()
LIMIT 3
SELECT *
FROM table1
WHERE id NOT IN (?, ?, ?, ?, ?)
ORDER BY RAND()
LIMIT 3
精彩评论