dqcuq4138 2012-02-29 03:49
浏览 24
已采纳

如何组合这些循环的MySQL查询?

I've recently began a comments/replies section for an app.
My initial approach has been to query the database for the comments linked to a particular item as below:-

$commentquery = "SELECT projects_comments.*, users.user_url, users.display_name
                   FROM ".$wpdb->prefix."projects_comments projects_comments
              LEFT JOIN ".$wpdb->prefix."users users on users.ID=projects_comments.userid
                  WHERE projectid = '$projectid'
               ORDER BY projects_comments.commentid DESC";  

I then began a foreach loop with the following query inside in order to retrieve the replies:

if($comments) {
  foreach ( $comments as $c ) { 
    $replyquery = "SELECT project_replies.*, users.user_url, users.display_name
                     FROM ".$wpdb->prefix."project_replies project_replies
                LEFT JOIN ".$wpdb->prefix."users users on users.ID=project_replies.uid
                    WHERE project_replies.cid = '$c->commentid' 
                 ORDER BY project_replies.id DESC"; 
  }
}

In practice this is all working fine, however it strikes me that this is terribly inefficient and that there must be a way to retrieve all the data in one query. My concern is that with 100 comments on a page I will be performing 100 queries for the comments alone.

What is the best method to tackle this and how would I go about combining these queries to produce one large object/array with which to pull the data from.

Or alternatively, how can I at least prevent the 'query-within-the-loop'.

  • 写回答

3条回答 默认 最新

  • dpbv85276 2012-02-29 04:06
    关注
    SELECT c.*, cu.user_url AS cu_url, cu.display_name AS cu_name,
           r.*, ru.user_url AS ru_url, ru.display_name AS ru_name
      FROM projects_comments AS c
      LEFT JOIN users        AS cu ON cu.ID = c.userid
      JOIN project_replies   AS r  ON r.cid = c.commentid 
      LEFT JOIN users        AS ru ON ru.ID = r.uid
     WHERE c.projectid = $projectid
     ORDER BY c.commentid DESC, r.id DESC
    

    The only detail to worry about is the JOIN instead of possibly using LEFT JOIN when connecting Project_Replies and Project_Comments. This will only pick up comments that have at least one reply; using a LEFT JOIN, you'll get comments that have no replies too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c