首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加载注释时的联接查询

加载注释时的联接查询
EN

Stack Overflow用户
提问于 2013-06-28 15:39:04
回答 3查看 66关注 0票数 1

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

代码语言:javascript
复制
$get_comments = mysql_query("SELECT * FROM  products_comments WHERE product_id = '3'");

现在我想为每个评论添加"report abuse“选项,为此,我有另一个表"abuse_reports”,它的用户滥用报告将存储在这个表中。现在,如果一个用户报告了一个评论,report abuse选项应该不再存在于该用户的评论中,为此,我正在执行以下操作:

代码语言:javascript
复制
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>";
}

使用上面的代码,对于每个注释,我进行了一个新的查询,这显然是错误的,我应该如何将第二个查询与第一个查询连接起来?

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-28 15:52:12

已更新查询(现已生效,已由提问者提交)

代码语言:javascript
复制
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

该查询的工作原理如下:选择具有给定product_idproducts_comments的所有字段,但也计算给定product_idabuse_reports条目。现在对abuse_reports执行LEFT JOIN操作,这意味着您要访问该表并将其挂在左侧( products_comments表)。外部允许在abuse_reports表中不需要值,因此如果没有报告,您将得到null,因此计数为0。

请阅读:然而,我需要对结果进行分组,否则您只会得到一个合并的行作为结果。因此,请使用类型为int的字段comment_id来扩展您的products_comments,该字段是primary key,并且具有auto_increment

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

代码语言:javascript
复制
$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;

只是一个原始样本

票数 1
EN

Stack Overflow用户

发布于 2013-06-28 15:46:21

我相信你正在寻找一个类似这样的查询。

代码语言:javascript
复制
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'"
票数 0
EN

Stack Overflow用户

发布于 2013-06-28 15:50:09

尝试使用此SQL

代码语言:javascript
复制
 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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17359628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档