简体   繁体   English

合并计数主题、评论和最后评论日期论坛 sql

[英]merge count number of topics, comments and last comment date forum sql

Im developing a forum-like website I want to put the next information within a div我正在开发一个类似论坛的网站,我想将下一个信息放在 div 中

 Category: Cars
 Topics: 27  Comments:5436
 Last Comment: 01.04.2020 //php formated

Here I count the number of posts这里我统计帖子数

   SELECT * 
   FROM posts as p
   WHERE p.category= :category 

   $sql->execute();

Here I count the number of comments这里我统计评论数

   SELECT * 
   FROM comments as c
   LEFT JOIN posts as p ON c.id_post = p.id_post
   WHERE p.category= :category 

   $sql->execute();

Here I find the last comment date在这里我找到最后评论日期

   SELECT max(c.date) as maxdate
   FROM comments as c
   LEFT JOIN posts as p ON c.id_post = p.id_post
   WHERE p.category= :category 
   GROUP BY c.id_comment

   $sql->execute();

My greatest probles is How should I merge all those three sql sentences and 3 pdo execution in one single sql statement (single pdo execution)?我最大的问题是我应该如何将所有这三个 sql 句子和 3 个 pdo 执行合并到一个 sql 语句中(单个 ZCF646305563A60207D3 执行)?

You can join and aggregate.您可以加入和聚合。 Consider:考虑:

select 
    p.category,
    count(distinct p.id_posts) no_posts,
    count(c.id_post)           no_comments,
    max(c.date)                date_last_comment
from posts p
left join comments c on c.id_post = p.id_post
where p.category= :category 
group by p.category

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM