简体   繁体   中英

How do I retrieve a random (but unique for a date) primary key value?

I have about 10,000 products in the product table. I want to retrieve one of those items and display it in a section of a web page which stays the same for that particular day. Something like "Product of the day".

For example, if today I get product_id 100, then all of the visitors should be viewing this product item for today. Tomorrow it may fetch any random valid primary key, say, 1289 and visitors get 1289 product all day tomorrow.

Any ideas/suggestions?

Thanks for your help.

SELECT  id
FROM    products
ORDER BY
        RAND(UNIX_TIMESTAMP(CURRENT_DATE()))
LIMIT 1

How about create a cache file and invalidate it at midnight?

The benefit of this is you don't make unnecessary calls to your DB as you're only checking the timestamp on the cache file - only once per day do you make DB requests to populate a new cache file.

You don't need a CRON job for this:

if(date_of_file(potd_cache_file) != today){
  potd_cache_file = generate_from_db();
}
load_file(potd_cache_file);

This will mean only the first visitor of the day to your website will trigger the regeneration, and every subsequent visitor will have a fast loading cache file served to them.

也许您可以将当天的项目ID存储在数据库的表中?

The idea is pretty simple,

  1. Set a table up call ProductOfTheDay with a product ID and a date field
  2. On the product of the day page when a user visits check the date field
  3. If it is todays date then show the product
  4. If it is not then randonly pick a new product and save it to the field.

Its not that complex of an operation.

SELECT  id
FROM    products
ORDER BY (id + RAND(UNIX_TIMESTAMP(CURRENT_DATE()))) MOD some_reasonable_value
LIMIT 1

You can start random number generators with a seed value.

Make the seed value be the day (21st) + month(10) + year(2009) so today's seed is 2041.

You will get the same random number all day, and tomorrow a different one. This is more how it works in .net. The random function takes a max and min value (this is your min and max ID values) then an optional seed value and returns a number. For the same seed number you get the same random number generated. It's possible if you change the max and min this can affect the number generated. You would have to look up how php works.

total = SELECT COUNT(id) FROM products;
day_product = SELECT id FROM products WHERE id = (UNIX_TIMESTAMP(CURRENT_DATE()) MOD total) LIMIT 1;

See also this question .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM