gpt4 book ai didi

php - 当有数千个条目时如何加快数据库查询

转载 作者:行者123 更新时间:2023-11-29 08:22:33 24 4
gpt4 key购买 nike

为了学习 php 和 codeigniter,我已经开始创建测试网站......类似于博客。但这不是重点。我正在使用 codeigniter 分页来显示我的所有博客帖子。但是......当我的数据库表(帖子)有超过 14k 条目时,它开始变慢......而且我不需要这样的答案:“如果它是博客,并且你永远不会写那么多帖子,那么就不要”不要考虑这个“......我需要真正的解决方案来加快所有这些事情。

这是 Controller :

    function all()
{
// Pagination $config
$config = $this->m_posts->getPaginationConfig('all', $this->m_posts->getPostsCount());
$this->pagination->initialize($config);
$data['posts'] = $this->m_posts->getAllPosts($config['per_page'], $page);
$data['pagination'] = $this->pagination->create_links();

$this->template->build('posts/posts', $data);
}

型号:

    function getPaginationConfig($base_url, $total_rows)
{
$config['base_url'] = base_url() . 'posts/'. $base_url;
$config['total_rows'] = $total_rows;
// ----
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['use_page_numbers'] = TRUE;
$config['uri_segment'] = 3;
return $config;
}
function getPostsCount($limit)
{
$this->db->order_by('id', 'desc');
$q = $this->db->get('posts');
return $q->num_rows();
}

function getAllPosts($limit = 0, $start = 0)
{
$this->db->order_by('id', 'desc');
$this->db->where('active', 1);
// Get LATEST posts -> pagination
$q = $this->db->get('posts', $limit, $start);
$array = $q->result_array();
$data = $this->createPostsArray($array);
return $data;
}
function createPostsArray($array)
{
foreach ($array as $key => $row)
{
$array[$key]['usr_info'] = $this->user->getUserData($row['usr_id'], 'nickname');
$this->load->helper('cat_helper');
$array[$key]['cat_ids'] = explodeCategories($row['cat_ids']);
foreach ($array[$key]['cat_ids'] as $numb => $value)
{
$array[$key]['categories'][$numb] = $this->getCategoryName($value);
}
}

return $array;
}

最佳答案

首先,将 getPostsCount 函数更改为此

function getPostsCount () {
return $this->db->count_all('posts');
}

你现在这样做的方式是浪费时间/内存/CPU 和代码行。

第二件事,使用左/内连接来获取其他数据,而不是在 foreach 语句中抛出一堆查询(这是错误的)。

如果您在连接事物方面仍需要帮助,请显示表结构以获得更多帮助。

我认为这个微小的改变会带来很大的改变。

编辑:

提供更多信息后,这是您的查询,并加入了用户(因为不清楚您的类别是如何工作的,所以我不包括它)。

function getAllPosts($limit = 0, $start = 0) {
$q = $this->db->select('p.*, u.nickname')
->from('posts p')
->join('users u', 'p.user_id = u.id', 'left')
->limit($limit, $start)
->get();
return $q->result_array();
}

这将返回带有用户昵称的帖子,至于类别,不清楚您如何存储它们,也不清楚爆炸类别正在做什么,如果您将它们存储在逗号分隔的字段中,您可以使用使用 ->where_in('id', array_of_ids); 获取所有类别的单个查询;

您需要阅读手册才能获得有关如何操作的更多帮助: http://ellislab.com/codeigniter/user-guide/

关于php - 当有数千个条目时如何加快数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com