我有一个存储评论的表。注释具有不同的深度级别,并且在具有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))");
是否可以通过一个查询来获取它们?
答案 0 :(得分:0)
您可以创建递归函数/方法,这将为您执行此循环。或使用do-while
构造:
$parentIds = null;
do {
$where = (is_null($parentIds)) ? 'IS NULL' : sprintf('IN (%s)', implode(',', $parentIds));
$query = $this->db->query("SELECT title FROM comment WHERE parent_id " . $where);
// Do something with $query data
// In your process $query loop you must fill $parentIds with `parent_id` column value
// ...
$parentIds[] = $row['parent_id'];
// ...
} while (!empty($parentIds));
答案 1 :(得分:0)
SELECT c1.title AS lev1, c2.title as lev2, c3.title as lev3
FROM comment AS C1
LEFT JOIN category AS c2 ON c2.parent_id = c1.id
LEFT JOIN category AS c3 ON c3.parent_id = c2.id
WHERE c1.parent_id IS NULL;
答案 2 :(得分:0)
由于级别的最大深度为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 |