我在 CodeIgniter 中具有从 2 个表中检索最新帖子的功能:
public function get_latest_comments($amount)
{
$query = $this->db->query('
SELECT *, FROM_UNIXTIME(date) AS timestamp
FROM comments
ORDER BY timestamp DESC
LIMIT 5
');
if ($query->num_rows() > 0) {
$result = $query->result_array();
for ($i = 0; $i < sizeof( $result ); $i++) {
$result[$i]['author_info'] = $this->comments_model->get_comment_author( $result[$i]['id'] );
$result[$i]['date'] = mdate( "%M %m, %Y", $result[$i]['date'] );
if ($result[$i]['section'] === 'blog') $loc = 'blog_posts';
if ($result[$i]['section'] === 'core') $loc = 'public_posts';
$this->db->select( 'title, slug' );
$query = $this->db->get_where( $loc, array('id' => $result[$i]['location']) );
$result[$i]['post_title'] = $query->row( 'title' );
$result[$i]['url'] = base_url() . $result[$i]['section'] . '/view/' . $query->row( 'slug' ) . '/';
}
return $result;
}
return false;
}
问题是它运行得太慢了。我的页面有时会加载 7-8 秒。我怀疑这个查询运行 2 次 + 收集最新评论的类似查询会减慢我的页面速度。
我对循环内的查询有一种不好的感觉。我怎样才能避免这种情况?
我的表的结构是:
users (id, username, mail ...
user_info ( user_id, name, surname
public_posts ( id, slug, text, author(user id) ...
blog_posts ( id, slug, text ...
comments ( id, text, author, location(post_id_, section(post_table) ...