php - 选择具有三个级别的评论

标签 php mysql sql

我有一个存储评论的表。评论有不同的深度,它们在一张表中与 id 和 parent_id 有关系。深层的最大值是三个,我想用一个查询而不是三个查询来选择它们,并使用 foreach 三次。

评论表:

id title                           parent_id 
 1 'where are you?'                NULL
 2 "im at home"                       1
 3 "what is time in your country?" NULL 
 4 "it's 3 pm"                        3
 5 "oh that's cool"                   4

第一层是 parent_id = NULL 的评论 我使用这些查询来获取它们:

$first = $this->db->query("SELECT title FROM comment WHERE parent_id IS NULL");
    $second = $this->db->query("SELECT title FROM comment WHERE parent_id IN (SELECT id FROM comment WHERE parent_id IS NULL)");
        $third= $this->db->query("SELECT title FROM comment WHERE parent_id IN (SELECT id FROM comment WHERE parent_id IN(SELECT id FROM comment WHERE parent_id IS NULL))");

有没有办法通过一次查询获取它们?

最佳答案

由于层级的最大深度为 3,我们可以利用两个自连接来确定父级 ID,并使用自定义排序。

如果您的 MySQL/MariaDB 版本不支持递归 CTE,请尝试以下解决方案:

模式(MySQL v5.7)

CREATE TABLE comment
    (`id` int, `title` varchar(33), `parent_id` varchar(4))
;

INSERT INTO comment
    (`id`, `title`, `parent_id`)
VALUES
    (1, 'where are you?', NULL),
    (2, 'what is time in your country?', NULL),
    (3, 'im at home', '1'),
    (4, 'its 3 pm', '2'),
    (5, 'oh thats cool', '4')
;

查询#1

SELECT c1.id, c1.title, c1.parent_id 
FROM comment AS c1 
LEFT JOIN comment AS c2 ON c2.id = c1.parent_id 
LEFT JOIN comment AS c3 ON c3.id = c2.parent_id 
ORDER BY 
  CASE WHEN c1.parent_id IS NULL THEN c1.id  /* first level comment*/
       WHEN c2.parent_id IS NULL THEN c2.id  /* second level comment */
       ELSE c3.id /* comment is at third level */
  END ASC, 
  c1.id ASC;

| id  | title                         | parent_id |
| --- | ----------------------------- | --------- |
| 1   | where are you?                |           |
| 3   | im at home                    | 1         |
| 2   | what is time in your country? |           |
| 4   | its 3 pm                      | 2         |
| 5   | oh thats cool                 | 4         |

View on DB Fiddle

关于php - 选择具有三个级别的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57675885/

相关文章:

php - Magento 事件调度/观察/修改调度对象

php - 不支持填写表格 FDDF FPDF-Merge Error Fast Web View 模式

php - SQL 从表中选择匹配的最低 ID 的所有行

mysql - 在现有列的值中添加字符

mysql - 选择查询中的临时变量赋值/增量

php - 在PHP中插入大量数据时如何回显数字序列?

php插入数据库值变为0

php - 当我使用 PDO PHP 查询 MySQL 数据库时出现令人困惑的错误

python - 如何获得由 4 个第一个字符组成的行?

php - "Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in"