gpt4 book ai didi

mysql - 最好关闭表 SELECT QUERY

转载 作者:行者123 更新时间:2023-11-29 04:28:03 24 4
gpt4 key购买 nike

我正在为 MySQL 和 PHP 开发线程评论系统。我选择了 Closure Table 模式,但我遇到了问题。我需要查询(查询)来获取整棵树。怎么做?我对此进行了很多搜索,但找不到最佳选择。如果您有更好的线程评论,请告诉我。感谢您的回复。

最佳答案

如果这个用例在您的应用程序中很常见,只需存储根 ID(树根的 ID。这可以是这些评论所属的帖子的 ID)。现在,当您需要获取整个评论树时,您只需要做:

SELECT * FROM comments WHERE root_id = <root_id>

或针对您的设计的等效查询。如果您提供表定义,我可以帮助您解决特定问题。

更新:

$dbh = new PDO($dsn, $user, $password);
$sql = "SELECT A.*, GROUP_CONCAT(descendant) as descendants FROM Comments AS A INNER JOIN Paths AS B ON A.id = B.ancestor WHERE A.item = ? GROUP BY A.id";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($item));
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

$adjacency_list = array(); $comments = array();
foreach($data as $row) {
$comments[$row['id']] = $row;
$descendants = explode(',', $row['descendants']);
$adjacency_list[$row['id']] = $descendants;
}

echo '<UL>';
foreach($adjacency_list[$item] as $top_level_comment) {
printTree($top_level_comment, $adjacency_list[$top_level_comment]);
}
echo '</UL>';

function printTree($node, $descendants) {
echo '<LI>'.$node;
if(sizeof($descendants) > 0) {
echo '<UL>';
foreach($descendants as $descendant) {
$d = array();
if(!empty($adjacency_list[$descendant])) $d = $adjacency_list[$descendant];
printTree($descendant, $adjacency_list[$descendant]);
}
echo '</UL>';
}
echo '</LI>';
}

另一方面,由于高插入和更新,嵌套集模型不是评论系统的好的解决方案。如果您的数据很少更新,这是一种有效的解决方案。

关于mysql - 最好关闭表 SELECT QUERY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7487189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com