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.
SELECT FLOOR(RAND() * COUNT(*)) INTO @offset FROM banners;
SELECT * FROM banners LIMIT @offset, 1;
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;
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
您将根据可用ID创建一个数组,并从该数组生成随机数
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.