PHP/MYSQL 父子关系
我有一个像这样的表:
- id
- name
- Parent_id
然后我想根据它们的 id 选择某些行,所以像这样:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
我想从这个查询中也显示父/子关系,例如:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
所以最终的输出将看起来像这样:
1
--5
8
--9
----35
我是否在 mysql 之外执行此操作,我尝试过使用数组,但无法弄清楚,或者
我是在MYSQL里面做的吗,我也不知道怎么做。
I have a table like this:
- id
- name
- parent_id
I then want to select certain rows based on their id, so something like this:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
I want to, from this query, also show the parent/child relationship, like:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
So the final output would look something like this:
1
--5
8
--9
----35
Do I do this outside of mysql, i have tried using arrays, but can't figure it out, or
Do I do it inside MYSQL, which i don't know how to do that either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我能得到的,看起来效果很好。
PS-抱歉格式问题,无法弄清楚:((已修复?)$testarray[$id] = $parent_id;
然后运行它通过下面的函数,它会按照我需要的方式进行排序。
Here is what I was able to come with which seems to be working great.
PS-Sorry about the formatting, can't figure it out :((fixed?)$testarray[$id] = $parent_id;
Then I run it through the functions below, and it orders it just how I need it.
在不改变表结构的情况下,这需要递归,而 MySQL 不支持递归。你必须在其他地方做这件事。您可以在 PHP 中编写递归函数来使用,例如 广度优先搜索构建你的数组。在这里,您似乎使用 0 的
parent_id
来表示顶级对象。您可以搜索结果,并将父级为零的每个对象添加到数组中,这将为您提供一个包含 1 和 8 的数组。然后您可以递归:找到父级为 1 的所有结果,并将其添加为子数组为 1;然后找到父级为 8 的所有结果,并将它们添加为 8 的子数组。对每个级别继续执行此操作,直到用完结果为止。正如其他发帖者指出的那样,如果您可以更改表结构,则可以在 MySQL 中本地执行此操作。
Without changing your table structure, this requires recursion, which MySQL does not support. You'll have to do it elsewhere. You can write a recursive function in PHP to use, for example, breadth-first search to build your array. Here it looks like you are using
parent_id
of 0 to denote a top-level object. You can search over your results, and add to your array every object whose parent is zero, which will give you an array with 1 and 8. Then you can recurse: find all the results with a parent of 1, and add that as a subarray to 1; then find all the results with a parent of 8 and add those as a subarray of 8. Continue doing this for each level until you've run out of results.As other posters pointed out, you can do this natively in MySQL if you can change the table structure.