0

我有这些 sql 查询(我使用 codeigniter db 类):

        $query = $this->db->select("a.title AS articles_title, 
                    a.content AS articles_content,
                    a.excerpt AS articles_excerpt,
                    a.slug AS articles_slug,
                    a.views AS articles_views,
                    a.views AS articles_views,
                    CONCAT(up.first_name, ' ', up.last_name) AS articles_author,
                    DATE_FORMAT(a.created, '%T %d.%m.%Y') AS articles_created, 
                    (SELECT IF(ROUND(AVG(av.vote),1), ROUND(AVG(av.vote),1), 0)  FROM articles_votes av WHERE a.id = av.article_id) AS articles_votes,
                    (SELECT COUNT(ac.id) FROM articles_comments ac WHERE a.id = ac.article_id) AS articles_totalcomments", FALSE)
            ->from('articles a')
            ->join('user_profiles up', 'a.author_id = up.user_id')
            ->where('page_id', $page_id)
            ->order_by("a.$ordering")
            ->get();

对服务器资源和速度有好处吗?或者我应该创建另一个计算投票和评论的函数,它将计算所有评论和平均投票,然后将其添加到文章数组中?

谢谢

4

1 回答 1

0

使用的资源和查询计划的效率取决于底层数据库,当然还有生成的实际 SQL。最好使用 SQL 分析工具来确保您了解查询的实际结果。

那就是说。有时您可以通过以下方式获得更好的性能:

SELECT 
   a.student_id, 
   a.name, 
   (select sum(s.score) from scores s where s.student_id = a.student_id) as total_score
FROM students a

对于这样的事情:

SELECT
   a.student_id,
   a.name,
   tot.score
FROM students a
JOIN (
   SELECT student_id, 
          sum(score)
   FROM scores 
   GROUP BY student_id
) as tot ON tot.student_id = a.student_id

如果您的列表达式涉及对未索引列的查询,则每次运行时可能需要进行全表扫描。在我的示例中,我在连接结果中包含一个键,因此查询完成一次,然后您可以在外部选择中获取它。

希望有帮助。

于 2012-08-23T07:31:27.440 回答