我应该在 sql 还是 php 中使用循环?

发布于 2025-01-02 03:01:28 字数 575 浏览 3 评论 0原文

可能的重复:
什么是将平面表解析为树的最有效/优雅的方法?
php/Mysql最佳树形结构

我的数据库中有一个表,其中充满了组,每个 组行有一个父id,直到最后一个父id为0,形成一个金字塔。例如:

id:1 姓名:工作人员 父级:0

ID:2 名称:通讯组 父级:1

ID:3 名称:网络部 Parent: 2

现在这可以永远持续下去,所以我想做的是使用一个 sql 语句给出 Web 部门 id,它将拉取所有父组,直到父组为 0。

在 sql 中这可能吗陈述?我怎么能这么做呢?

Possible Duplicate:
What is the most efficient/elegant way to parse a flat table into a tree?
php / Mysql best tree structure

I have a table in my database full of groups, each group row has a parent id until the last parent id is 0, making a pyramid. For example:

id: 1
name: staff
parent: 0

id: 2
name: communications team
parent: 1

id: 3
name: web department
parent: 2

Now that can go on forever down the lines, so what I want to do is by using one sql statement giving the web department id it will pull all of the parent groups until the parent is 0.

Is that possible within an sql statement? How could I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风情万种。 2025-01-09 03:01:28

我认为你根本不需要循环...只是 T-SQL 中类似的东西:

SELECT id, name, parent
FROM tablename
WHERE parent <= (select parent from tablename where name = 'staff')
ORDER BY parent;

这应该返回父 id 小于或等于员工父 id 的所有行。如果您希望以其他方式排序,请改用 ORDER BY 父 ASC。

I don't think you need a loop at all... just something like this in T-SQL:

SELECT id, name, parent
FROM tablename
WHERE parent <= (select parent from tablename where name = 'staff')
ORDER BY parent;

This should return all rows where the parent id is less than or equal to the parent id of staff. If you want it ordered the other way, use ORDER BY parent ASC instead.

桜花祭 2025-01-09 03:01:28

您从 sql 中提取可能需要的所有内容,然后使用 PHP 中的递归函数来遍历结果。寻找 PHP 递归树。

You pull everything that you might need from the sql and then use a recursive function in PHP to walk through the results. Look for PHP recursive trees.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文