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

时间:2012-02-29 03:49:05

标签: php mysql

我最近开始为应用添加评论/回复部分 我最初的方法是在数据库中查询链接到特定项目的注释,如下所示: -

$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";  

然后我开始在foreach循环中使用以下查询来检索回复:

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"; 
  }
}

在实践中,这一切都运行正常,但是我觉得这非常低效并且必须有一种方法来检索一个查询中的所有数据。我担心的是,在页面上有100条评论,我将仅对评论进行100次查询。

解决此问题的最佳方法是什么?如何组合这些查询以生成一个用于从中提取数据的大型对象/数组。

或者,我怎样才能至少阻止'在循环中查询'。

3 个答案:

答案 0 :(得分:2)

我倾向于避免这种设置:

SELECT ...
WHERE `keyfield` IN (".implode(",",$keyvalues).")

答案 1 :(得分:2)

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

唯一需要担心的细节是JOIN,而不是在连接Project_Replies和Project_Comments时可能使用LEFT JOIN。这只会收到至少有一条回复的评论;使用LEFT JOIN,您将收到没有回复的评论。

答案 2 :(得分:1)

你可以JOINusers

那样 $commentquery = "SELECT projects_comments.*, project_replies.*, users.user_url, users.display_name, users2.user_url as comment_user_url, users2.display_name as comment_display_name from ".$wpdb->prefix."projects_comments projects_comments LEFT JOIN ".$wpdb->prefix."project_replies project_replies ON project_replies.cid = projects_comments.comment_id LEFT JOIN ".$wpdb->prefix."users users on users.ID=project_replies.uid left join ".$wpdb->prefix."users users2 on users2.ID=projects_comments.userid WHERE projectid = '$projectid' ORDER BY projects_comments.commentid desc, project_replies.id DESC";
{{1}}