1

我正在为 id = '3' 的产品加载评论

$get_comments = mysql_query("SELECT * FROM  products_comments WHERE product_id = '3'");

现在我想为每条评论添加“报告滥用”选项,为此我有另一个表作为“ abuse_reports”,用户滥用报告将存储在此表中,现在如果用户报告了评论,该report abuse选项不应该在那里为该用户发表评论,为此我正在做:

while($row = mysql_fetch_array($get_comments)){
   echo blah blah blah // comment details
   // now for checking if this user should be able to report this or not, i make this query again:
   $check_report_status = mysql_query("SELECT COUNT(id) FROM abuse_reports WHERE reporter_user_id = '$this_user_id' AND product_id = 'this_product_id'");
   // blah blah count the abuse reports which the current user made for this product
   if($count == 0) echo "<a>report abuse</a>";
}

使用上面的代码,对于每条评论,我都会进行一个新查询,这显然是错误的,我应该如何将第二个查询与第一个查询结合起来?

谢谢

4

3 回答 3

1

更新的查询(现在正在工作,由提问者提交)

SELECT pc. * , count( ar.`id` ) AS `abuse_count`
FROM `products_comments` pc
LEFT OUTER JOIN `abuse_reports` ar ON pc.`id` = ar.`section_details`
AND ar.`reporter_id` = '$user_id'
WHERE pc.`product_id` = '$product_id'
GROUP BY pc.`id`
LIMIT 0 , 30

查询的工作方式如下:您products_comments使用给定选择您的所有字段,product_id但您还计算给定的abuse_reports条目product_id。现在LEFT JOINabuse_reports,这意味着您可以访问该表并将其挂在左侧(您的 products_comments 表)。OUTER 允许在 abuse_reports 表中不需要值,因此如果没有报告,您将获得空值,因此计数为 0。

请阅读以下内容: 但是,我需要对结果进行分组,否则您只会得到一个合并行作为结果。因此,请使用and has类型的字段扩展您products_comments的字段。comment_idintprimary keyauto_increment

更新:滥用计数 现在您可以做两件事:通过遍历结果,您可以查看每个元素是否已被该用户报告(例如,您可以隐藏滥用报告链接)。如果您想要报告的总数,您只需增加一个在循环外声明的计数器变量。像这样:

$abuse_counter = 0;
while($row = mysql....)
{
  $abuse_counter += intval($row['abuse_count']);   // this is 1 or 0
  // do whatever else with that result row
}

echo 'The amount of reports: '.$abuse_counter;

只是一个原始样本

于 2013-06-28T07:52:11.680 回答
0

试试这个 SQL

 SELECT pc.*, COUNT(ar.id) AS abuse_count
 FROM  products_comments pc
      LEFT JOIN abuse_reports ar ON pc.product_id = ar.product_id
 WHERE pc.product_id = '3' AND ar.reporter_user_id = '$this_user_id'
 GROUP BY pc.product_id

如果reporter_user_id 存在,结果是带有abuse_reports 计数的products_comments 列表

于 2013-06-28T07:50:08.713 回答
0

我相信您正在寻找这样的查询。

SELECT pc.*, COUNT(ar.*) 
FROM  products_comments AS pc
LEFT JOIN abuse_reports AS ar ON reporter_user_id = pc.user_id AND ar.product_id = pc.product_id
WHERE product_id = '3'"
于 2013-06-28T07:46:20.877 回答