Reputation: 7960
I have a "banners" table which has image names and paths to image files that will be randomly viewed each time visitor navigates to another page.
banners table consists of banner_id (auto_increment, unique, primary, tinyint), banner_name (varchar) and banner_path (varchar) fields.
Banners table will be editable via a control panel. New banners will be ADDED, some banner will be DELETED after a while, and may be UPDATED. General CRUD operations, you know...
Now... Because of my goal is showing banners randomly, I will need a random number generator function which gives ability to exclude specific ones.
To be more clear,
Let's say my table looks like this:
banner_id banner_name banner_path
--------- ------------ ------------
1 First Banner first_banner.jpg
2 Second Banner second_banner.jpg
3 Third Banner third_banner.jpg
I can get random ID by using PHP function like this easily: mt_random(1, 3);
But wait. What if I delete one of these banners?
banner_id banner_name banner_path
--------- ------------ ------------
1 First Banner first_banner.jpg
3 Third Banner third_banner.jpg
In this case, as random output becomes "2", what will happen? There is no a "2" banner_id'd row?? So I must exclude DELETED id's from random generator number range. Will this be the best practise? If so, how can I do that?
I'm completly open for any new ideas which will help me to do thing I want to do.
Please help me to figure out this problem...
Thanks
Thanks.
Upvotes: 2
Views: 2141
Reputation: 65314
Assuming you can live with the small race window, you could do
SELECT FLOOR(RAND()*COUNT(*)) AS bannercount FROM banners;
and fetch this into $bannercount
, next run
SELECT * FROM banners ORDER BY banner_id LIMIT $bannercount,1
Upvotes: 0
Reputation: 125955
SELECT FLOOR(RAND() * COUNT(*)) INTO @offset FROM banners;
SELECT * FROM banners LIMIT @offset, 1;
Upvotes: 1
Reputation: 599
you will create one array from available ids and generate random numbers from that array
Upvotes: 0
Reputation: 9299
Why not just select a random row instead of using PHP to select a random ID to show?
SELECT * FROM `banners` ORDER BY RAND() LIMIT 0,1;
And if you have an array of ID's to exclude
SELECT * FROM `banners`
WHERE `banner_id` NOT IN (/* array values*/)
ORDER BY RAND() LIMIT 0,1;
Upvotes: 0