Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial mysql千万级数据怎么做优化

mysql千万级数据怎么做优化

Jun 23, 2016 pm 01:39 PM

function insert(){		global $m;		if (!isset($_REQUEST['strs']) || !isset($_REQUEST['type'])			 || !isset($_REQUEST['hash'])){			echo 'param error';			return;		}		//strs为所有字符串		$poststr = $_REQUEST['strs'];        		$xstrs = json_decode(stripslashes($poststr), true);        		$type = $_REQUEST['type'];		$hash = $_REQUEST['hash'];				if (count($xstrs) <= 0){			$msg = 'str error';			DsLog::errLog($msg.$poststr);			echo $msg;			return;		}		if ($type == '0'){			$table = 'white';		}		else if($type == '1'){			$table = 'black';		}		else{			$msg = 'type error';			DsLog::errLog($msg);			echo $msg;			return;		}        $strs = array();        		for($i = 0; $i < count($xstrs); $i++) {            $strtmp = $xstrs[$i];            $strtmp = trim($strtmp);            $strtmp = strtolower($strtmp);	    	$strtmp = addslashes($strtmp);            if (strlen($strtmp) > 256){				$strtmp = substr($strtmp, 0, 256);			}            if (strlen($strtmp) >= 7)            {                array_push($strs, $strtmp);            }	    }                		//拼接所有字符串		$tmp = '("'.implode('","', $strs).'")';		//获取已存在的字符串		$sql = "select * from $table where str in $tmp";		$ret = mysql_query($sql, $m);		if (!$ret){			$msg = 'exec error:'.mysql_error($m).','.$sql;			DsLog::errLog($msg);			echo $msg;			return;		}		$exists = array();		$notexists = array();		$count = mysql_num_rows($ret);		for ($i = 0; $i < $count; $i++)		{			$item = mysql_fetch_assoc($ret);			if (!$item){				break;			}			array_push($exists, $item['str']);		}				for ($i = 0; $i < count($strs); $i++){			if (in_array($strs[$i], $exists)){				continue;			}			array_push($notexists, $strs[$i]);		}		for($i = 0; $i < count($exists); $i++) {	    	$exists[$i] = addslashes($exists[$i]);	    }	    for($i = 0; $i < count($notexists); $i++) {	    	$notexists[$i] = addslashes($notexists[$i]);	    }				if (count($exists) > 0){			//更新已存在字符串的count字段			$tmp = '("'.implode('","', $exists).'")';			$time = date('YmdHi');			$sql = "update $table set count=count+1 where str in $tmp";			$ret = mysql_query($sql, $m);			if (!$ret){				$msg = 'exec error:'.mysql_error($m).','.$sql;				DsLog::errLog($msg);				echo $msg;				return;			}			//更新已存在字符串的upd字段			$sql = "update $table set upd='$time' where str in $tmp";			$ret = mysql_query($sql, $m);			if (!$ret){				$msg = 'exec error:'.mysql_error($m).','.$sql;				DsLog::errLog($msg);				echo $msg;				return;			}		}						//插入新信息		if (count($notexists) > 0){			$time = date('YmdHi');			$sql = "insert ignore into $table (str,hash,count, upd) values";			for ($i = 0; $i < count($notexists); $i++){				$str = $notexists[$i];				$crc = sprintf("%u", crc32($str));				$sql .= "('$str','$crc','1', '$time'),";			}			$sql = substr($sql, 0, strlen($sql) - 1);			$ret = mysql_query($sql, $m);			if (!$ret){				$msg = 'insert error:'.mysql_error($m).','.$sql;				DsLog::errLog($msg);				echo $msg;				return;			}		}				echo !!$ret;	}
Copy after login


我现在要对字符串做统计,统计每个字符串的数量,就是类似一个map, 这符串:数量,当然,数据库顺便还保存了一下字符中的crc等信息
insert函数接收post过来的strs,这是一个字符串数组,每次post过来的字符串数量平均为1500
现在数据库里的记录1200W条,每一次insert花费的时间平均为20秒(经常出现30秒超时)
请问下各位,该怎么做优化,现在只是统计了很小一部分,预计统计完数据量大概在1-10亿条


回复讨论(解决方案)

对了,str字段做了唯一索引,其它字段没做,mysql为MyISAM

你能确定瓶颈是在数据库做 查询 和 修改 的3条语句上吗?
你说 每次post过来的字符串数量平均为1500
那是指 1500 的单词吗?就算不是(是串长度)那么以平均每个单词20个字符计算,也有75个单词
你的过滤条件是 str in $tmp (str in ('xxx','xxx'....))也就是对表中的每一条记录都要做 1500(75)次字符串比较,而命中率至多是1/1500(1/75)你认为这样做合适吗?
数据库的强项在于记录间的比较,而你却在做弱势的列间比较
你可以用传入的数据构造出一个临时表(每行一个单词),再去与主表关联操作。这样才能发挥数据库的优势

再有,你的连续 2 条 update 语句不能合并在一起吗?

你能确定瓶颈是在数据库做 查询 和 修改 的3条语句上吗?
你说 每次post过来的字符串数量平均为1500
那是指 1500 的单词吗?就算不是(是串长度)那么以平均每个单词20个字符计算,也有75个单词
你的过滤条件是 str in $tmp (str in ('xxx','xxx'....))也就是对表中的每一条记录都要做 1500(75)次字符串比较,而命中率至多是1/1500(1/75)你认为这样做合适吗?
数据库的强项在于记录间的比较,而你却在做弱势的列间比较
你可以用传入的数据构造出一个临时表(每行一个单词),再去与主表关联操作。这样才能发挥数据库的优势

再有,你的连续 2 条 update 语句不能合并在一起吗?



1500是指字符数,字符数应该在5W左右

你的意思是先把1500条记录insert到一个临时表tmp_table,然后
然后 select* from table inner join tmp_talbe on table.str = tmp_table.str 这样么?

你能确定瓶颈是在数据库做 查询 和 修改 的3条语句上吗?
你说 每次post过来的字符串数量平均为1500
那是指 1500 的单词吗?就算不是(是串长度)那么以平均每个单词20个字符计算,也有75个单词
你的过滤条件是 str in $tmp (str in ('xxx','xxx'....))也就是对表中的每一条记录都要做 1500(75)次字符串比较,而命中率至多是1/1500(1/75)你认为这样做合适吗?
数据库的强项在于记录间的比较,而你却在做弱势的列间比较
你可以用传入的数据构造出一个临时表(每行一个单词),再去与主表关联操作。这样才能发挥数据库的优势

再有,你的连续 2 条 update 语句不能合并在一起吗?



1500是字符串数,大概3W个字符
你的意思是把1500个字符中插入到临时表tmp里,然后再 select* from white inner join tmp on white.str=tmp.str 么?
我刚测了下
select* from white inner join tmp on white.str=tmp.str 执行时间10S
id 	select_type 	table 	type 	possible_keys 	key 	key_len 	ref 	rows 	Extra1 	SIMPLE 	tmp 	index 	str 	str 	770 	NULL 	2531 	Using index1 	SIMPLE 	white 	eq_ref 	str 	str 	770 	bayes.tmp.str 	1 	 
Copy after login


直接执行 select * from white where str in(''xxx','xxx'...) 执行时间9S
id 	select_type 	table 	type 	possible_keys 	key 	key_len 	ref 	rows 	Extra1 	SIMPLE 	white 	range 	str 	str 	770 	NULL 	2531 	Using where
Copy after login


感觉效果差不多一样

1、mysql 有内存表,你并未使用
2、将两条 update 合并,应该能减少 10 秒

mysql_error这种库函数的效率也不高吧而且官方也不推荐,我几乎没有用过这种,我学PHP的时候,直接开始PDO的。

还有,你用了in这个关键字,好像它是不走索引的吧。

感觉效果差不多一样


应该是你测试环境的问题吧,联表查询大多数情况下是要比in快的
你测的结果差不多可能是如下原因
1.查询表的数据没有达到一定量
2.两种查询方式查出的结果集不同
3.查询字段未加索引或加的不对
4.被其他索引过多而影响
5.其他原因
我认为比较明显的就是第2个原因
你联表查时没有指定查询字段,联表出的字段肯定要比不连表的要多
还有联表查询会有一对多的情况,那样一条记录就会变成多条的,要加group by
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.

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.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles