我正在阅读书籍 SQL反模式 并试图理解其利用自引用表构建“树”的示例,如下所示:
Comments
-------------------------------------------------------------------
comment_id | parent_id | author | comment
-------------------------------------------------------------------
1 NULL Fran What's the cause of this bug?
2 1 Ollie I think it's a null pointer.
3 2 Fran No, I checked for that.
4 1 Kukla We need to check for invalid input.
5 4 Ollie Yes, that's a bug.
6 4 Fran Yes, please add a check.
7 6 Kukla That fixed it.
所以这本书说:
我正在尝试理解它是如何工作的。我一直以来对于表格You can retrive a comment and its immediate children using a relatively simple query:
SELECT c1.*, c2.* FROM Comments c1 LEFT OUTER JOIN Comments c2 ON c2.parent_id = c1.comment_id
t1
和t2
之间的左外连接理解是,您需要从t1
中取出所有行,并且对于不满足ON
子句的行,您需要为第二个表中的列填充NULL
。在这种情况下只有一个表格,但我可以想象查询是在两个表格中进行的,其中第二个表格是第一个表格的副本。即使如此,我仍然不明白该查询返回了什么。
请问结果表格是什么样的,您能否向我讲述产生它的逻辑?树的两个级别。