MySQL query to return a fraction of the rows in the table each day

时间:2015-08-07 02:44:36

标签: mysql

I am attempting to write a query that will give me a fraction of all the rows in a table but a different fraction each day. Lets say I will run this query once a day each week. I want 1/7 of the rows in the table. Suppose I had a table with one column like this:

CREATE TABLE `active_databases` (
`database_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`database_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Put some sample data into it:

INSERT INTO `active_databases` (`database_name`) VALUES ('db1'),('db2'),('db3'),('db4'),('db5'),('db6'),('db7'),('db8'),('db9'),('db10');

If I run my query on Monday I would want it to give me the first 1/7 of those rows rounded up. Then again on Tuesday give me the next 1/7 of the rows but not the ones from Monday. Then Wednesday give me the next 1/7 of the rows but not the ones from Monday/Tuesday and so on. The following week the query will start over again and return the first 1/7 of the rows and continue.

How could this query be written?

1 个答案:

答案 0 :(得分:0)

我不认为这里有一个查询就足够了。 您可以做的是向架构添加一个字段。如果尚未使用该记录,则该字段的值为0,如果已经使用,则该值为1.

然后使用count(*)计算出架构中的记录数量,我们会将该值存储在total_records中。

您可以做的是选择此标志设置为0的所有记录,但选择不超过总大小的1/7。

如果len_div_7占有total_records/7,您可以使用此查询来完成上述操作:

select * from mytable where flag=0 limit len_div_7

所以你得到了你的1/7。

现在,您希望确保更新记录,以便下次不通过浏览每条记录并将flag更新为1来选择它们。

如果在某些时候,您选择的小于1/7(例如,如果总记录可被7整除,则不会选择它们),这意味着您需要再次循环,因此将所有记录的标志重置为0。

注意:如果表中的记录数在整个星期内发生变化,则解决方案会发生变化。这是假设大小是固定的。