I have a table of urls. I need to select 1, in round robin. Hoping to display 1 per pageview OR per Visitor and show each 20 times if I have 100 pageviews OR Visitors.
Essentially: SELECT url FROM table LIMIT 1
(in rotation)
+-------+---------------------+
| id | url |
+-------+---------------------+
| 1 | http://google.com |
| 2 | http://yahoo.com |
| 3 | http://ebay.com |
| 4 | http://anything.com |
| 5 | http://other.com |
+-------+---------------------+
If I understand correctly what you mean by round-robin then you can do something along the lines of
SELECT id, url
FROM urls u CROSS JOIN
(
SELECT MIN(id) min_id, MAX(id) max_id
FROM urls
) m
WHERE id > IF(? >= max_id, 0, ?) -- last shown id goes here instead of placeholders
ORDER BY id
LIMIT 1;
Store (in session, file, another table, etc.) and pass to your query the last shown id
or 0 for the initial query.
This will give you the next row or first again if you reached the last one. This query will still work if you have gaps in id
s.
Here is a SQLFiddle demo
You can use RAND()
function in your ORDER BY
clause:
SELECT * FROM tableName ORDER BY RAND() LIMIT 1
Is this what you want to achieve?
You can do using order by rand()
SELECT * FROM table ORDER BY rand() LIMIT 1