我正在尝试从具有随机日期范围的表中进行选择。像
这样的东西SELECT * FROM my_table WHERE timestamp
BETWEEN <random_date> AND <the_same_random_date> - INTERVAL 1 DAY
那样我应该选择一个随机日期1天的间隔。有什么建议吗?
更新:因此,随机查询可能与以下查询具有相同的效果:
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-08-05 00:00' AND '2011-08-05 00:00' - INTERVAL 1 DAY
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-08-12 14:30' AND '2011-08-12 14:30' - INTERVAL 1 DAY
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-05-11 06:15' AND '2011-05-11 06:15' - INTERVAL 1 DAY
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-03-03 21:11' AND '2011-03-03 21:11' - INTERVAL 1 DAY
答案 0 :(得分:1)
SELECT *
FROM
my_table
CROSS JOIN (SELECT FROM_UNIXTIME(RAND() * 2147483647) random_date) rd
WHERE
timestamp BETWEEN (rd.random_date - INTERVAL 1 DAY) AND rd.random_date
答案 1 :(得分:1)
使用BETWEEN时,必须先使用较小(较早)的值。例如,而不是
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-08-05 00:00' AND '2011-08-05 00:00' - INTERVAL 1 DAY
你想要使用
SELECT * FROM my_table WHERE timestamp
BETWEEN '2011-08-05 00:00' - INTERVAL 1 DAY AND '2011-08-05 00:00'
您是否在询问如何使用MySQL生成这些随机日期?或者你只是想知道为什么你的查询不起作用?如果你想要生成随机日期,那么Karolis的答案对你来说应该是很好的。