mysql程序块,MySQL:按块检索较大的选择

本文介绍如何在Windows 2012 R2环境下,通过分批(LIMIT)从MySQL表中提取超过7000万行数据,并避免内存溢出。方法包括使用LIMIT功能,将数据切分成小块保存至临时表,最后逐步导出为CSV文件。同时,文章提醒了处理过程中的注意事项,如实时冻结结果和数据一致性问题。
摘要由CSDN通过智能技术生成

I have select with more then

70 milion rows

I'd like to save the selected data into the one large csv file on win2012 R2

Q: How to retrive the data from MySQL by chanks for better performance ?

because when I try to save one the large select I got

out of memory errors

解决方案

You could try using the LIMIT feature. If you do this:

SELECT * FROM MyTable ORDER BY whatever LIMIT 0,1000

You'll get the first 1,000 rows. The first LIMIT value (0) defines the starting row in the result set. It's zero-indexed, so 0 means "the first row". The second LIMIT value is the maximum number of rows to retrieve. To get the next few sets of 1,000, do this:

SELECT * FROM MyTable ORDER BY whatever LIMIT 1000,1000 -- rows 1,001 - 2,000

SELECT * FROM MyTable ORDER BY whatever LIMIT 2000,1000 -- rows 2,001 - 3,000

And so on. When the SELECT returns no rows, you're done.

This isn't enough on its own though, because any changes done to the table while you're processing your 1K rows at a time will throw off the order. To freeze the results in time, start by querying the results into a temporary table:

CREATE TEMPORARY TABLE MyChunkedResult AS (

SELECT *

FROM MyTable

ORDER BY whatever

);

Side note: it's a good idea to make sure the temporary table doesn't exist beforehand:

DROP TEMPORARY TABLE IF EXISTS MyChunkedResult;

At any rate, once the temporary table is in place, pull the row chunks from there:

SELECT * FROM MyChunkedResult LIMIT 0, 1000;

SELECT * FROM MyChunkedResult LIMIT 1000,1000;

SELECT * FROM MyChunkedResult LIMIT 2000,1000;

.. and so on.

I'll leave it to you to create the logic that will calculate the limit value after each chunk and check for the end of results. I'd also recommend much larger chunks than 1,000 records; it's just a number I picked out of the air.

Finally, it's good form to drop the temporary table when you're done:

DROP TEMPORARY TABLE MyChunkedResult;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值