我有这个模特
<?php
class Cities_model extends CI_Model {
protected $table = 'cities';
public function __construct() {
parent::__construct();
}
public function get_count() {
return $this->db->count_all($this->table);
}
public function get_cities($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get($this->table);
return $query->result();
}
}
和该控制器
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Cities extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->helper('url');
$this->load->model('cities_model');
$this->load->library("pagination");
}
public function index() {
$config = array();
$config["base_url"] = base_url() . "cities";
$config["total_rows"] = $this->cities_model->get_count();
$config["per_page"] = 10;
$config["uri_segment"] = 2;
$this->pagination->initialize($config);
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$data["links"] = $this->pagination->create_links();
$data['cities'] = $this->cities_model->get_cities($config["per_page"], $page);
$this->load->view('show_grid', $data);
}
}
我在mysql中有超过200万条记录,并且生成了链接。但是,加载需要20秒。
我认为get_count()花费的时间太长。有什么办法可以使加载时间从20秒减少?
答案 0 :(得分:1)
我想说get_count()
函数肯定是引起您问题的原因。
我可能会创建一个表来存储总数。然后,在添加/删除某些内容时,您只需添加一个或减去一个即可。然后,您只需获得该数字,它几乎立即就会发生。
您还可以考虑使用caching计数或使用database cache(警告,除非您确切了解其工作原理,否则请不要使用数据库缓存)。请注意,这些方法还需要对记录的添加/删除进行一些干预。在缓存方面,您必须使cache variable无效。数据库缓存具有类似的功能:https://www.codeigniter.com/user_guide/database/caching.html#this-db-cache-delete-all