Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial mysql表列复制,mysql连接时间和内存控制。

mysql表列复制,mysql连接时间和内存控制。

Jun 23, 2016 pm 02:10 PM

有两个表临时表temp_t,和正表table1,都是MyISAM,分别有28W条左右的记录。
cron定时每分钟从网络上获取一些信息,先存储到temp_t(频繁写入),
然后cron定时每10分钟从temp_t复制信息到正表table1(频繁读取,每10分钟写一次)。

temp_t字段 id(auto_increment),title(varchar(200)),content(varchar(500)),date(DATETIME), mykey(tinyint(1) Default 1, 这个来判别是否已经复制到正表,复制过后UPDATE为2)

table1字段 id(没有auto_increment),title(varchar(200)),content(varchar(500)),date(DATETIME)


28W记录,每个数据表大概有300MB,每次更新差不多要2K-3K条记录。
如果直接复制的话,MYSQL连接时间过长,导致MYSQL性能下降table1会出现类似于锁表的现象,查询table1的时间明显加长

require dirname(__FILE__) . '/../connection.php';mysql_select_db("news",$connextion);mysql_query("SET NAMES utf8");$query = mysql_query("SELECT * FROM temp_t where mykey = '1'");while($rows = mysql_fetch_array($query)){	mysql_query("UPDATE temp_t SET mykey='2' WHERE id='".mysql_real_escape_string($rows['id'])."'");	mysql_query("INSERT INTO table1 (id,title,content,date) values ('".mysql_real_escape_string($rows['id'])."','".mysql_real_escape_string($rows['title'])."','".mysql_real_escape_string($rows['content'])."','".mysql_real_escape_string($rows['date'])."'");}mysql_close($connextion);
Copy after login



于是想先把记录从temp_t里的数据先读出来,存为一个json数组,然后再复制数据到table1,但是有时会遇到Cannot allocate memory,然后导致整个服务器崩溃(是不是这个json数组太大,占了巨量的内存)。PS:已经在php.ini里将memory limit加到64M了(但总觉得治标不治本,这么一个复制过程,不需要那么多内存,关键还是代码不合理)。

require dirname(__FILE__) . '/../connection.php';mysql_select_db("news",$connextion);mysql_query("SET NAMES utf8");$query = mysql_query("SELECT * FROM temp_t where mykey = '1'");$jon = array();while($rows = mysql_fetch_array($query)){	$jon['a'] = $rows['id'];	$jon['b'] = $rows['title'];	$jon['c'] = $rows['content'];	$jon['d'] = $rows['date'];	$pjon .= json_encode($jon).',';}mysql_close($connextion);$njso = json_decode('['.substr($pjon,0,-1).']');foreach($njso as $nx){		if($nx->a){		require dirname(__FILE__) . '/../connection.php';		mysql_select_db("news",$connextion);		mysql_query("SET NAMES utf8");		mysql_query("UPDATE temp_t SET mykey='2' WHERE id='".mysql_real_escape_string($nx->a)."'");		mysql_query("INSERT INTO table1 (id,title,content,date) values ('".mysql_real_escape_string($nx->a)."','".mysql_real_escape_string($nx->b)."','".mysql_real_escape_string($nx->c)."','".mysql_real_escape_string($nx->d)."'");		mysql_close($connextion);	}}
Copy after login


所以求助大虾们,有没有更节省的代码用来复制表的信息?要求mysql连接时间短,内存消耗又少?谢谢大家。


回复讨论(解决方案)

依次执行这两句就可以了
INSERT INTO table1 (id,title,content,date) values
SELECT id, title,content,date from temp_t where mykey = '1'

UPDATE temp_t SET mykey='2' WHERE mykey = '1'

不需劳驾 php 转交

既然 temp_t 是临时存放,那么转移后的数据为何不删除呢?

依次执行这两句就可以了
INSERT INTO table1 (id,title,content,date) values
SELECT id, title,content,date from temp_t where mykey = '1'

UPDATE temp_t SET mykey='2' WHERE mykey = '1'

不需劳驾 php 转交

既然 temp_t 是临时存放,那么转移后的数据为何不删除呢?

temp_t的数据还不能删,insert时还有一个判断,就是title不重复(避免重复插入)
按照老大的意思,这样执行就可以了?还没测试,得停掉cron脚本。
弱弱的问一句,依老大的经验,300MB数据表,像这样一次插入2000-3000条记录,这个脚本大概要运行多长时间,耗费多少内存?是不是my.cnf里要增加某些值的内存,用来加速INSERT和SELECT的执行时间?再次感谢。

require dirname(__FILE__) . '/../connection.php';mysql_select_db("news",$connextion);mysql_query("SET NAMES utf8");$query = mysql_query("INSERT INTO table1 (id,title,content,date) values SELECT id, title,content,date from temp_t where mykey = '1'");$query = mysql_query("UPDATE temp_t SET mykey='2' WHERE mykey = '1'");}mysql_close($connextion);
Copy after login

1:首先临时表,又没对外读取?如果有为啥不memcache,然后table1在去读取memcache回来?

2:300m 不算大吖。别人文学站,冬不冬一个表就上10G的。一样复制来去。

3:以前公司做个项目,1个表就400万条数据,采用的方法,从临时表里,1条1条的读取,慢慢读,不用把所有事情挤在一起来出来,这样虽然是时时刻刻的运行着,总共比卡死好吖。

1:首先临时表,又没对外读取?如果有为啥不memcache,然后table1在去读取memcache回来?

内存本来就不够,还装memcache……人家是nginx服务器集群,俺这块是几十元的虚拟空间……

10G的表复制,是不是my.cnf里需要增加某些值的大小?
总感觉自己的表300M运行速度慢,还经常卡死。人家天文数字,频繁读写的照样工作顺畅。


1:首先临时表,又没对外读取?如果有为啥不memcache,然后table1在去读取memcache回来?

内存本来就不够,还装memcache……人家是nginx服务器集群,俺这块是几十元的虚拟空间……

10G的表复制,是不是my.cnf里需要增加某些值的大小?
总感觉自己的表300M运行速度慢,还经常卡死。人家天文数字,频繁读写的照样工作顺畅。


那你是用第三条好点,无论你多大多复杂的数据,1条1条的来。1-2秒1条,1天下来也很恐怖了。
没必要一次倒那么多出去的,如果非的一次倒,多大的集团公司也不敢这样做的。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles