php教程 php手册 提高MySQL数据库查询效率的几个技巧[php程序员必看]

提高MySQL数据库查询效率的几个技巧[php程序员必看]

Jun 13, 2016 am 11:21 AM
mysql php 여러 개의 그리고 콤팩트 기능 개선하다 작동하다 능률 데이터 베이스 질문 ~의 프로그램 제작자

MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.

l
使用statement进行绑定查询
使用statement可以提前构建查询语法树,在查询时不再需要构建语法树就直接查询.因此可以很好的提高查询的效率. 这个方法适合于查询条件固定但查询非常频繁的场合.
使用方法是:

绑定, 创建一个MYSQL_STMT变量,与对应的查询字符串绑定,字符串中的问号代表要传入的变量,每个问号都必须指定一个变量.
查询, 输入每个指定的变量, 传入MYSQL_STMT变量用可用的连接句柄执行.
代码如下:

//1.绑定
bool CDBManager::BindInsertStmt(MYSQL * connecthandle)
{
       //作插入操作的绑定
       MYSQL_BIND insertbind[FEILD_NUM];
       if(m_stInsertParam == NULL)
              m_stInsertParam = new CHostCacheTable;
       m_stInsertStmt = mysql_stmt_init(connecthandle);
       //构建绑定字符串
       char insertSQL[SQL_LENGTH];
       strcpy(insertSQL, "insert into HostCache(SessionID, ChannelID, ISPType, "
              "ExternalIP, ExternalPort, InternalIP, InternalPort) "
              "values(?, ?, ?, ?, ?, ?, ?)");
       mysql_stmt_prepare(m_stInsertStmt, insertSQL, strlen(insertSQL));
       int param_count= mysql_stmt_param_count(m_stInsertStmt);
       if(param_count != FEILD_NUM)
              return false;
       //填充bind结构数组, m_sInsertParam是这个statement关联的结构变量
       memset(insertbind, 0, sizeof(insertbind));
       insertbind[0].buffer_type = MYSQL_TYPE_STRING;
       insertbind[0].buffer_length = ID_LENGTH /* -1 */;
       insertbind[0].buffer = (char *)m_stInsertParam->sessionid;
       insertbind[0].is_null = 0;
       insertbind[0].length = 0;

       insertbind[1].buffer_type = MYSQL_TYPE_STRING;
       insertbind[1].buffer_length = ID_LENGTH /* -1 */;
       insertbind[1].buffer = (char *)m_stInsertParam->channelid;
       insertbind[1].is_null = 0;
       insertbind[1].length = 0;

       insertbind[2].buffer_type = MYSQL_TYPE_TINY;
       insertbind[2].buffer = (char *)&m_stInsertParam->ISPtype;
       insertbind[2].is_null = 0;
       insertbind[2].length = 0;

       insertbind[3].buffer_type = MYSQL_TYPE_LONG;
       insertbind[3].buffer = (char *)&m_stInsertParam->externalIP;
       insertbind[3].is_null = 0;
       insertbind[3].length = 0;


       insertbind[4].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[4].buffer = (char *)&m_stInsertParam->externalPort;
       insertbind[4].is_null = 0;
       insertbind[4].length = 0;

       insertbind[5].buffer_type = MYSQL_TYPE_LONG;
       insertbind[5].buffer = (char *)&m_stInsertParam->internalIP;
       insertbind[5].is_null = 0;
       insertbind[5].length = 0;

       insertbind[6].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[6].buffer = (char *)&m_stInsertParam->internalPort;
       insertbind[6].is_null = 0;
       insertbind[6].is_null = 0;
       //绑定
       if (mysql_stmt_bind_param(m_stInsertStmt, insertbind))
              return false;
       return true;
}

//2.查询
bool CDBManager::InsertHostCache2(MYSQL * connecthandle, char * sessionid, char * channelid, int ISPtype,
              unsigned int eIP, unsigned short eport, unsigned int iIP, unsigned short iport)
{
       //填充结构变量m_sInsertParam
       strcpy(m_stInsertParam->sessionid, sessionid);
       strcpy(m_stInsertParam->channelid, channelid);
       m_stInsertParam->ISPtype = ISPtype;
       m_stInsertParam->externalIP = eIP;
       m_stInsertParam->externalPort = eport;
       m_stInsertParam->internalIP = iIP;
       m_stInsertParam->internalPort = iport;
       //执行statement,性能瓶颈处
       if(mysql_stmt_execute(m_stInsertStmt))
              return false;
       return true;
}

l
随机的获取记录
在某些数据库的应用中, 我们并不是要获取所有的满足条件的记录,而只是要随机挑选出满足条件的记录. 这种情况常见于数据业务的统计分析,从大容量数据库中获取小量的数据的场合.

有两种方法可以做到
1.       常规方法,首先查询出所有满足条件的记录,然后随机的挑选出部分记录.这种方法在满足条件的记录数很多时效果不理想.
2.       使用limit语法,先获取满足条件的记录条数, 然后在sql查询语句中加入limit来限制只查询满足要求的一段记录. 这种方法虽然要查询两次,但是在数据量大时反而比较高效.
示例代码如下:

//1.常规的方法
//性能瓶颈,10万条记录时,执行查询140ms, 获取结果集500ms,其余可忽略
int CDBManager::QueryHostCache(MYSQL* connecthandle, char * channelid, int ISPtype, CDBManager::CHostCacheTable * &hostcache)
{

       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));
       sprintf(selectSQL,"select * from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       //获取结果集
       m_pResultSet = mysql_store_result(connecthandle);
       if(!m_pResultSet)   //获取结果集出错
              return 0;
       int iAllNumRows = (int)(mysql_num_rows(m_pResultSet));      ///       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows        if(iReturnNumRows        {
              //获取逐条记录
              for(int i = 0; i              {
                     //获取逐个字段
                     m_Row = mysql_fetch_row(m_pResultSet);
                     if(m_Row[0] != NULL)
                            strcpy(hostcache.sessionid, m_Row[0]);
                     if(m_Row[1] != NULL)
                            strcpy(hostcache.channelid, m_Row[1]);
                     if(m_Row[2] != NULL)
                            hostcache.ISPtype      = atoi(m_Row[2]);
                     if(m_Row[3] != NULL)
                            hostcache.externalIP   = atoi(m_Row[3]);
                     if(m_Row[4] != NULL)
                            hostcache.externalPort = atoi(m_Row[4]);
                     if(m_Row[5] != NULL)
                            hostcache.internalIP   = atoi(m_Row[5]);
                     if(m_Row[6] != NULL)
                            hostcache.internalPort = atoi(m_Row[6]);             
              }
       }
       else
       {
              //随机的挑选指定条记录返回
              int iRemainder = iAllNumRows%iReturnNumRows;    ///              int iQuotient = iAllNumRows/iReturnNumRows;      ///              int iStartIndex = rand()%(iRemainder + 1);         ///

              //获取逐条记录
        for(int iSelectedIndex = 0; iSelectedIndex         {
                            mysql_data_seek(m_pResultSet, iStartIndex + iQuotient * iSelectedIndex);
                            m_Row = mysql_fetch_row(m_pResultSet);
                  if(m_Row[0] != NULL)
                       strcpy(hostcache[iSelectedIndex].sessionid, m_Row[0]);
                   if(m_Row[1] != NULL)
                                   strcpy(hostcache[iSelectedIndex].channelid, m_Row[1]);
                   if(m_Row[2] != NULL)
                       hostcache[iSelectedIndex].ISPtype      = atoi(m_Row[2]);
                   if(m_Row[3] != NULL)
                       hostcache[iSelectedIndex].externalIP   = atoi(m_Row[3]);
                    if(m_Row[4] != NULL)
                       hostcache[iSelectedIndex].externalPort = atoi(m_Row[4]);
                   if(m_Row[5] != NULL)
                       hostcache[iSelectedIndex].internalIP   = atoi(m_Row[5]);
                   if(m_Row[6] != NULL)
                       hostcache[iSelectedIndex].internalPort = atoi(m_Row[6]);
        }
      }
       //释放结果集内容
       mysql_free_result(m_pResultSet);
       return iReturnNumRows;
}

//2.使用limit版
int CDBManager::QueryHostCache(MYSQL * connecthandle, char * channelid, unsigned int myexternalip, int ISPtype, CHostCacheTable * hostcache)
{
       //首先获取满足结果的记录条数,再使用limit随机选择指定条记录返回
       MYSQL_ROW row;
       MYSQL_RES * pResultSet;
       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));

       sprintf(selectSQL,"select count(*) from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)      
              return 0;
       row = mysql_fetch_row(pResultSet);
       int iAllNumRows = atoi(row[0]);
       mysql_free_result(pResultSet);
       //计算待取记录的上下范围
       int iLimitLower = (iAllNumRows               0:(rand()%(iAllNumRows - RETURN_QUERY_HOST_NUM));
       int iLimitUpper = (iAllNumRows               iAllNumRows:(iLimitLower + RETURN_QUERY_HOST_NUM);
       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows                iAllNumRows:RETURN_QUERY_HOST_NUM;


       //使用limit作查询
       sprintf(selectSQL,"select SessionID, ExternalIP, ExternalPort, InternalIP, InternalPort "
              "from HostCache where ChannelID = '%s' and ISPtype = %d limit %d, %d"
              , channelid, ISPtype, iLimitLower, iLimitUpper);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)
              return 0;
       //获取逐条记录
       for(int i = 0; i       {
              //获取逐个字段
              row = mysql_fetch_row(pResultSet);
              if(row[0] != NULL)
                     strcpy(hostcache.sessionid, row[0]);
              if(row[1] != NULL)
                     hostcache.externalIP   = atoi(row[1]);
              if(row[2] != NULL)
                     hostcache.externalPort = atoi(row[2]);
              if(row[3] != NULL)
                     hostcache.internalIP   = atoi(row[3]);
              if(row[4] != NULL)
                     hostcache.internalPort = atoi(row[4]);            
       }
       //释放结果集内容
       mysql_free_result(pResultSet);
       return iReturnNumRows;
}

l
使用连接池管理连接.
在有大量节点访问的数据库设计中,经常要使用到连接池来管理所有的连接.
一般方法是:建立两个连接句柄队列,空闲的等待使用的队列和正在使用的队列.
当要查询时先从空闲队列中获取一个句柄,插入到正在使用的队列,再用这个句柄做数据库操作,完毕后一定要从使用队列中删除,再插入到空闲队列.
设计代码如下:

//定义句柄队列
typedef std::list CONNECTION_HANDLE_LIST;
typedef std::list::iterator CONNECTION_HANDLE_LIST_IT;

//连接数据库的参数结构
class CDBParameter

{
public:
       char *host;                                 ///       char *user;                                 ///       char *password;                         ///       char *database;                           ///       unsigned int port;                 ///       const char *unix_socket;      ///       unsigned int client_flag; ///};

//创建两个队列
CONNECTION_HANDLE_LIST m_lsBusyList;                ///CONNECTION_HANDLE_LIST m_lsIdleList;                  ///

//所有的连接句柄先连上数据库,加入到空闲队列中,等待使用.
bool CDBManager::Connect(char * host /* = "localhost" */, char * user /* = "chenmin" */,
                                           char * password /* = "chenmin" */, char * database /* = "HostCache" */)
{
       CDBParameter * lpDBParam = new CDBParameter();
       lpDBParam->host = host;
       lpDBParam->user = user;
       lpDBParam->password = password;
       lpDBParam->database = database;
       lpDBParam->port = 0;
       lpDBParam->unix_socket = NULL;
       lpDBParam->client_flag = 0;
       try
       {
              //连接
              for(int index = 0; index               {
                     MYSQL * pConnectHandle = mysql_init((MYSQL*) 0);     //初始化连接句柄
                     if(!mysql_real_connect(pConnectHandle, lpDBParam->host, lpDBParam->user, lpDBParam->password,
       lpDBParam->database,lpDBParam->port,lpDBParam->unix_socket,lpDBParam->client_fla))
                            return false;
//加入到空闲队列中
                     m_lsIdleList.push_back(pConnectHandle);
              }
       }
       catch(...)
       {
              return false;
       }
       return true;
}

//提取一个空闲句柄供使用
MYSQL * CDBManager::GetIdleConnectHandle()
{
       MYSQL * pConnectHandle = NULL;
       m_ListMutex.acquire();
       if(m_lsIdleList.size())
       {
              pConnectHandle = m_lsIdleList.front();      
              m_lsIdleList.pop_front();
              m_lsBusyList.push_back(pConnectHandle);
       }
       else //特殊情况,闲队列中为空,返回为空
       {
              pConnectHandle = 0;
       }
       m_ListMutex.release();

       return pConnectHandle;
}

//从使用队列中释放一个使用完毕的句柄,插入到空闲队列
void CDBManager::SetIdleConnectHandle(MYSQL * connecthandle)
{
       m_ListMutex.acquire();
       m_lsBusyList.remove(connecthandle);
       m_lsIdleList.push_back(connecthandle);
       m_ListMutex.release();
}
//使用示例,首先获取空闲句柄,利用这个句柄做真正的操作,然后再插回到空闲队列
bool CDBManager::DeleteHostCacheBySessionID(char * sessionid)
{
       MYSQL * pConnectHandle = GetIdleConnectHandle();
       if(!pConnectHandle)
              return 0;
       bool bRet = DeleteHostCacheBySessionID(pConnectHandle, sessionid);
       SetIdleConnectHandle(pConnectHandle);
       return bRet;
}
//传入空闲的句柄,做真正的删除操作
bool CDBManager::DeleteHostCacheBySessionID(MYSQL * connecthandle, char * sessionid)
{
       char deleteSQL[SQL_LENGTH];
       memset(deleteSQL, 0, sizeof(deleteSQL));
       sprintf(deleteSQL,"delete from HostCache where SessionID = '%s'", sessionid);
       if(mysql_query(connecthandle,deleteSQL) != 0) //删除
              return false;
       return true;
}


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

MySQL에 루트로 로그인 할 수 없습니다 MySQL에 루트로 로그인 할 수 없습니다 Apr 08, 2025 pm 04:54 PM

Root로 MySQL에 로그인 할 수없는 주된 이유는 권한 문제, 구성 파일 오류, 암호 일관성이 없음, 소켓 파일 문제 또는 방화벽 차단입니다. 솔루션에는 다음이 포함됩니다. 구성 파일의 BAND-ADDRESS 매개 변수가 올바르게 구성되어 있는지 확인하십시오. 루트 사용자 권한이 수정 또는 삭제되어 재설정되었는지 확인하십시오. 케이스 및 특수 문자를 포함하여 비밀번호가 정확한지 확인하십시오. 소켓 파일 권한 설정 및 경로를 확인하십시오. 방화벽이 MySQL 서버에 연결되는지 확인하십시오.

MySQL 테이블 잠금 테이블 변경 여부 MySQL 테이블 잠금 테이블 변경 여부 Apr 08, 2025 pm 05:06 PM

MySQL이 테이블 구조를 수정하면 메타 데이터 잠금 장치가 일반적으로 사용되므로 테이블을 잠글 수 있습니다. 자물쇠의 영향을 줄이려면 다음과 같은 조치를 취할 수 있습니다. 1. 온라인 DDL과 함께 테이블을 사용할 수 있습니다. 2. 배치에서 복잡한 수정을 수행합니다. 3. 소형 또는 피크 기간 동안 운영됩니다. 4. PT-OSC 도구를 사용하여 더 미세한 제어를 달성하십시오.

Redshift Zero ETL과의 RDS MySQL 통합 Redshift Zero ETL과의 RDS MySQL 통합 Apr 08, 2025 pm 07:06 PM

데이터 통합 ​​단순화 : AmazonRdsMysQL 및 Redshift의 Zero ETL 통합 효율적인 데이터 통합은 데이터 중심 구성의 핵심입니다. 전통적인 ETL (추출, 변환,로드) 프로세스는 특히 데이터베이스 (예 : AmazonRDSMySQL)를 데이터웨어 하우스 (예 : Redshift)와 통합 할 때 복잡하고 시간이 많이 걸립니다. 그러나 AWS는 이러한 상황을 완전히 변경 한 Zero ETL 통합 솔루션을 제공하여 RDSMYSQL에서 Redshift로 데이터 마이그레이션을위한 단순화 된 거의 실시간 솔루션을 제공합니다. 이 기사는 RDSMYSQL ZERL ETL 통합으로 Redshift와 함께 작동하여 데이터 엔지니어 및 개발자에게 제공하는 장점과 장점을 설명합니다.

MySQL이 여러 연결을 처리 할 수 ​​있습니다 MySQL이 여러 연결을 처리 할 수 ​​있습니다 Apr 08, 2025 pm 03:51 PM

MySQL은 여러 동시 연결을 처리하고 멀티 스레딩/다중 프로세싱을 사용하여 각 클라이언트 요청에 독립적 인 실행 환경을 할당하여 방해받지 않도록 할 수 있습니다. 그러나 동시 연결 수는 시스템 리소스, MySQL 구성, 쿼리 성능, 스토리지 엔진 및 네트워크 환경의 영향을받습니다. 최적화에는 코드 레벨 (효율적인 SQL), 구성 레벨 (Max_Connections 조정), 하드웨어 수준 (서버 구성 개선)과 같은 많은 요소를 고려해야합니다.

MySQL 사용자와 데이터베이스의 관계 MySQL 사용자와 데이터베이스의 관계 Apr 08, 2025 pm 07:15 PM

MySQL 데이터베이스에서 사용자와 데이터베이스 간의 관계는 권한과 테이블로 정의됩니다. 사용자는 데이터베이스에 액세스 할 수있는 사용자 이름과 비밀번호가 있습니다. 권한은 보조금 명령을 통해 부여되며 테이블은 Create Table 명령에 의해 생성됩니다. 사용자와 데이터베이스 간의 관계를 설정하려면 데이터베이스를 작성하고 사용자를 생성 한 다음 권한을 부여해야합니다.

MySQL은 Android에서 실행할 수 있습니다 MySQL은 Android에서 실행할 수 있습니다 Apr 08, 2025 pm 05:03 PM

MySQL은 Android에서 직접 실행할 수는 없지만 다음 방법을 사용하여 간접적으로 구현할 수 있습니다. Android 시스템에 구축 된 Lightweight Database SQLite를 사용하여 별도의 서버가 필요하지 않으며 모바일 장치 애플리케이션에 매우 적합한 작은 리소스 사용량이 있습니다. MySQL 서버에 원격으로 연결하고 데이터 읽기 및 쓰기를 위해 네트워크를 통해 원격 서버의 MySQL 데이터베이스에 연결하지만 강력한 네트워크 종속성, 보안 문제 및 서버 비용과 같은 단점이 있습니다.

MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 MySQL의 쿼리 최적화는 데이터베이스 성능을 향상시키는 데 필수적입니다. 특히 대규모 데이터 세트를 처리 할 때 Apr 08, 2025 pm 07:12 PM

1. 올바른 색인을 사용하여 스캔 한 데이터의 양을 줄임으로써 데이터 검색 속도를 높이십시오. 테이블 열을 여러 번 찾으면 해당 열에 대한 인덱스를 만듭니다. 귀하 또는 귀하의 앱이 기준에 따라 여러 열에서 데이터가 필요한 경우 복합 인덱스 2를 만듭니다. 2. 선택을 피하십시오 * 필요한 열만 선택하면 모든 원치 않는 열을 선택하면 더 많은 서버 메모리를 선택하면 서버가 높은 부하 또는 주파수 시간으로 서버가 속도가 느려지며, 예를 들어 Creation_at 및 Updated_at 및 Timestamps와 같은 열이 포함되어 있지 않기 때문에 쿼리가 필요하지 않기 때문에 테이블은 선택을 피할 수 없습니다.

MySQL : 초보자를위한 데이터 관리의 용이성 MySQL : 초보자를위한 데이터 관리의 용이성 Apr 09, 2025 am 12:07 AM

MySQL은 설치가 간단하고 강력하며 데이터를 쉽게 관리하기 쉽기 때문에 초보자에게 적합합니다. 1. 다양한 운영 체제에 적합한 간단한 설치 및 구성. 2. 데이터베이스 및 테이블 작성, 삽입, 쿼리, 업데이트 및 삭제와 같은 기본 작업을 지원합니다. 3. 조인 작업 및 하위 쿼리와 같은 고급 기능을 제공합니다. 4. 인덱싱, 쿼리 최적화 및 테이블 파티셔닝을 통해 성능을 향상시킬 수 있습니다. 5. 데이터 보안 및 일관성을 보장하기위한 지원 백업, 복구 및 보안 조치.

See all articles