如何用MySQL的子评论选择评论?

时间:2018-03-02 04:42:57

标签: php mysql

我有两张桌子:

'评论'

| id | content | user_id | article_id | parent_id |

'用户'

| id | name | photo |

我的疑问是:

<?php
$query = mysql_query("SELECT comments.id, comments.content, users.name, 
users.photo FROM comments, users WHERE comments.article_id = '".$get_id."' 
AND comments.parent_id = 0 AND comments.user_id = users.id");
while($res = mysql_fetch_assoc($query))
{
  $id = $res['id'];
  $content = $res['content'];
  $name = $res['name'];
  $photo = $res['photo'];

  echo $photo;
  echo $name;
  echo $content;

  $query2 = mysql_query("SELECT comments.id, comments.content, users.name, 
  users.photo FROM comments, users WHERE comments.article_id = '".$get_id."' 
AND comments.parent_id = '".$id."' AND comments.user_id = users.id");
  while($res2 = mysql_fetch_assoc($query2))
  {
    $id2 = $res2['id'];
    $content2 = $res2['content'];
    $name2 = $res2['name'];
    $photo2 = $res2['photo'];

    echo $photo2;
    echo $name2;
    echo $content2;
  }
}
?>

它无法正常工作。虽然有几个孩子评论,但它在每个巢中显示1个父母和1个孩子评论。

如何修复并最小化它?可以只使用一个查询来完成吗?

谢谢!

2 个答案:

答案 0 :(得分:-1)

JOIN表格本身。

将您的查询更改为:

SELECT comments.id, comments.content, users.name, 
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN 
comments c ON comments.id = 
c.parent_id  WHERE 
comments.article_id = '".$get_id."' 
AND comments.parent_id = '".$id."'

您不需要第二个查询,这里是完整的代码:

<?php

$query = mysql_query("SELECT comments.id, comments.content, users.name, 
users.photo FROM comments JOIN users ON comments.user_id = users.id JOIN 
comments c ON comments.id = 
c.parent_id  WHERE 
comments.article_id = '".$get_id."'");

while($res = mysql_fetch_assoc($query))
{
  $id = $res['id'];
  $content = $res['content'];
  $name = $res['name'];
  $photo = $res['photo'];

  echo $photo;
  echo $name;
  echo $content;
 } 

?>

答案 1 :(得分:-1)

只需使用JOIN即可获取评论以及所有孩子。

SELECT users.id userID, users.name, users.photo , childrenComments.*,   
   parentComments.id cpId, parentComments.content cpContent,
   parentComments.user_id cpUser_id,parentComments.article_id cpArticleId
FROM users JOIN (SELECT * FROM Comment WHERE id=0) parentComments 
ON users.id=parentComments.user_id LEFT JOIN Comment childrenComments
ON parentComments.id=childrenComments.parent_id;

然后你可以循环结果来适当地打印它。这样会更好,因为您只需要运行一个查询。