我正在为id = '3‘的产品加载评论
$get_comments = mysql_query("SELECT * FROM products_comments WHERE product_id = '3'");现在我想为每个评论添加"report abuse“选项,为此,我有另一个表"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>";
}使用上面的代码,对于每个注释,我进行了一个新的查询,这显然是错误的,我应该如何将第二个查询与第一个查询连接起来?
谢谢
发布于 2013-06-28 15:52:12
已更新查询(现已生效,已由提问者提交)
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_id的products_comments的所有字段,但也计算给定product_id的abuse_reports条目。现在对abuse_reports执行LEFT JOIN操作,这意味着您要访问该表并将其挂在左侧( products_comments表)。外部允许在abuse_reports表中不需要值,因此如果没有报告,您将得到null,因此计数为0。
请阅读:然而,我需要对结果进行分组,否则您只会得到一个合并的行作为结果。因此,请使用类型为int的字段comment_id来扩展您的products_comments,该字段是primary key,并且具有auto_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-28 15:46:21
我相信你正在寻找一个类似这样的查询。
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-28 15:50:09
尝试使用此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结果是具有abuse_reports计数products_comments列表,如果存在reporter_user_id的话
https://stackoverflow.com/questions/17359628
复制相似问题