sql - MySQL查询计数问题

标签 sql mysql

我正在尝试计算我的评论和回复数,但我似乎做错了。

到目前为止,这是我的查询。

SELECT posts_comments.*, users.* 
(SELECT COUNT(*)
FROM posts_comments 
WHERE parent_comment_id >= 1)
FROM posts_comments
LEFT JOIN users 
ON posts_comments.user_id = users.user_id
WHERE post_id = '" . $post_id . "'
AND parent_comment_id = 0
LIMIT $start, $display

这是我的 MySQL 表。

CREATE TABLE posts_comments (
comment_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_comment_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
post_id INT UNSIGNED NOT NULL,
comment TEXT NOT NULL,
PRIMARY KEY (id),
);

显示输出。

COMMENT 1
   comment 2
   comment 3
COMMENT 4
COMMENT 5

最佳答案

您无法在同一查询中获得父评论和子评论的计数。如果您想要像您发布的那样输出,则每次打 child 时都必须分开并发送查询。 (使用 for()) 或者有另一列并让您的程序分解结果。

此外,在您的查询中,您有 AND parent_comment_id = 0 而另一个 SELECT 有 AND parent_comment_id >= 1 这总是会给你带来零结果。

关于sql - MySQL查询计数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732592/

相关文章:

sql - 测量查询性能: "Execution Plan Query Cost" vs "Time Taken"

python - SQL 一对多关系 - 查询以检索 JSON 格式的数据

mysql没有使用索引

c# - MySQL ADO.Net 嵌套数据读取器

sql - Postgres 一贯偏爱嵌套循环连接而不是合并连接

java - 不必要的外键约束失败

python - pyODBC:在 Windows 中指定驱动程序的位置

mysql - 用 Mysql 配置 ejabberd,报错 p1_mysql.app not found

javascript - 在预定义的 Javascript 代码中导入 MySQL 表

php - 我如何在mysql中查询两个不同的表