Php 添加索引对查询时间的影响

Php 添加索引对查询时间的影响,php,mysql,codeigniter,Php,Mysql,Codeigniter,我正试图缩短查询时间。我正在使用codeigniter。。。表中记录小于等于100的查询。。。查询需要2毫秒。一个查询从表中获取1条记录,并且有2条where语句需要35毫秒。。。这个表有5000条记录 $this->db -> where ('DealSiteId', $q1['DealSiteId'] ); $this->db -> where ('DealUniqueId',$q1['DealUniqueId'] );

我正试图缩短查询时间。我正在使用codeigniter。。。表中记录小于等于100的查询。。。查询需要2毫秒。一个查询从表中获取1条记录,并且有2条where语句需要35毫秒。。。这个表有5000条记录

        $this->db -> where ('DealSiteId', $q1['DealSiteId'] );
        $this->db -> where ('DealUniqueId',$q1['DealUniqueId'] );

        $dup= $this-> db -> get ('deals');
        $dup1 = $dup -> result();


      if (count($dup1)!=0){

            $data['error']="Duplicate, This deal already exists. ";
            return $data;
        }

我在where子句中的两个字段上添加索引。。。索引类型为BTREE。有没有更快的方法来检查重复项?

如果您创建了包含两个字段的复合索引,您的查询可以使用一个索引来提高效率。

您是在两个字段上都添加了单独的索引,还是在一个合并的字段上添加了单独的索引

无论哪种方式,您都应该直接在mysql(或类似phpMyAdmin的东西)中测试您的查询,并使用
EXPLAIN
查看发生了什么:

在您的特定情况下,您可以为
DealSiteId
DealUniqueId
的组合添加
unique
索引/约束。这看起来像(未经测试,只是给你一个想法…):


确定查询是否尽可能高效的任何简单方法都是使用。要在CodeIgniter中执行此操作,可以执行以下操作:

$this->db->where('DealSiteId', $q1['DealSiteId'] );
$this->db->where('DealUniqueId',$q1['DealUniqueId'] );

$result = $this->db->get('deals');
echo $this->db->last_query();
获取打印的结果并对MySQL命令运行它:
EXPLAIN
,这将告诉您有关该查询的有用信息。i、 如果使用索引,扫描多少行,如果使用排序,创建临时表,等等。从那里你可以优化你的查询以获得最佳结果

$this->db->where('DealSiteId', $q1['DealSiteId'] );
$this->db->where('DealUniqueId',$q1['DealUniqueId'] );

$result = $this->db->get('deals');
echo $this->db->last_query();