I want to choose an entry from my database randomly, but not on every call, but depending on some other external factor as the week of the year, or the day of the year. How Can I achieve this?
This will tell me the current week:
SELECT DATE_FORMAT(CURDATE(),'%u');
So, to get an entry based on this value, I choose the entry number:
SELECT (DATE_FORMAT(CURDATE(),'%u')+0) MOD (SELECT COUNT(*)
FROM my_view
ORDER BY id);
So, my attempt:
SELECT * FROM my_view
LIMIT (SELECT (SELECT DATE_FORMAT(CURDATE(),'%u')+0) MOD (SELECT COUNT(*)
FROM my_view
ORDER BY id))
,1;
And all I get is this:
ERROR 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near '(SELECT (SELECT DATE_FORMAT(
CURDATE(),'%u')+0) MOD (SELECT COUNT(*) FROM ' at line 1
Maybe this is not the best approach? Is this not possible?
Thank you.
UPDATE: I want to insert this on a VIEW, so I can only use SELECT statements. Anyways, I’ve already solved this, please see this comment: Weekly-based ORDER BY on MySQL
The reason of the error you see is that
LIMITclause can take only literals as arguments, it doesn’t accept variables.If you want to select different (random) number of rows, you can create a function that accepts desired number of rows and in a loop select rows to the temporary table. After that you can just select everything from that table.
If you want to choose an entry based on some data, then you should play with
ORDER BYand select N first rows.