您好,欢迎访问一九零五行业门户网

怎么实现从数据查询数据的时候判断如果数据大于N条分次查询 递归吗?

比如数据库有300000条数据 现在根据条件查询符合的有30000条数据 一次取太多了可能慢或者其他问题 我想每次取10000 三次取完 这只是个例子 应该怎么实现啊?用递归吗?
告知下 谢谢!!!
还有就是如果查俩张表的数据 合并在一起 还有办法排序吗根据某个字段?
回复内容: 比如数据库有300000条数据 现在根据条件查询符合的有30000条数据 一次取太多了可能慢或者其他问题 我想每次取10000 三次取完 这只是个例子 应该怎么实现啊?用递归吗?
告知下 谢谢!!!
还有就是如果查俩张表的数据 合并在一起 还有办法排序吗根据某个字段?
谢邀,对于数据量较大的结果集,我目前一般采用以下两种方式处理。采用这两种方式处理的目的就是:一是减少数据集获取时带宽资源的占用,二是减少程序对结果集处理时内存的使用。
分块,就是题主的思路
$sql = 'select xxx from table where xxx limit limit :limit offset :offset';$limit = 10000;$offset = 0;do{ $stmt = $dbh->prepare($sql, array(pdo::attr_cursor => pdo::cursor_fwdonly)); $stmt->execute(array(':limit' => $limit, ':offset' => $offset)); $data = $stmt->fetchall(); // 处理逻辑 $offset += $limit;}while(count($data));
游标,按行读取返回
$sql = 'select xxx from table where xxx';$stmt = $dbh->prepare($sql, array(pdo::attr_cursor => pdo::cursor_scroll));$stmt->execute();$row = $stmt->fetch(pdo::fetch_num, pdo::fetch_ori_last);do { // 处理逻辑 $row} while ($row = $stmt->fetch(pdo::fetch_num, pdo::fetch_ori_prior));
个人建议当你要查找后面的分块的时候,用where条件而不是直接limit 100000 , 100000:
二者区别举例如下:
//这个是第一种,取第20w开始的10w条数据select * from table limit 100000 , 100000 order by id//这是第二种取法select * from table where id > 100000 limit 100000 order by id因为mysql用limit越往后,排序之后取后面的越慢
直接通过sql语句就能搞定呀,不需要后台处理;可以排序呀,根据你指定字段order by就行了
连表查询
例如:select a.* from tablea as a, tableb as b where a.id = b.id order by a.id desc limit 0,10000;
你可以先select count(1) from table where 条件。看看一共有多少数据。大于n条的时候,
你再select * from table limit m,n 分页查询
2张表的话就
select * from table1 union all select * form table2 order by 某个字段。注意查询的列数量要一样。最好类型也一样
假设表id均匀分布的情况下,可以利用id的区间来分段查询数据
//每次计划读取的数据条数$max_per_size = 10000;//找到符合条件的最小id和最大id$sql = select min(id),max(id) as max_id as num from `table` where xx='xx';$stmt = $pdo->prepare($sql);$stmt->execute();$res = $stmt->fetch(pdo::fetch_assoc);//符合条件的最大id$max_id = $res['max_id'];//符合条件的最小id$min_id = $res['min_id'];$times = ceil(($max_id - $min_id + 1) / $max_per_size);//第一次的id区间$current_min_id = $min_id;$current_max_id = $min_id + $max_per_page;for($i = 0; $i= {$current_min_id} and id $max_id) { $current_max_id = $max_id; }}
其它类似信息

推荐信息