使用 mysql/php 中的 id /parent_id 模型获取记录的所有父项的最简单方法是什么?
我正在寻找使用邻接列表/单表继承模型(id,parent_id
)从数据库递归获取所有父元素的最简单方法。
我的选择当前如下所示:
$sql = "SELECT
e.id,
TIME_FORMAT(e.start_time, '%H:%i') AS start_time,
$title AS title,
$description AS description,
$type AS type,
$place_name AS place_name,
p.parent_id AS place_parent_id,
p.city AS place_city,
p.country AS place_country
FROM event AS e
LEFT JOIN place AS p ON p.id = e.place_id
LEFT JOIN event_type AS et ON et.id = e.event_type_id
WHERE e.day_id = '$day_id'
AND e.private_flag = 0
ORDER BY start_time";
每个事件
都链接到一个地点
,并且每个地点
可以是另一个地点<的子级/code> (最多约 5 层深)
这可以在 mysql 的单次选择中实现吗?
目前我认为它可能是一个单独的函数,它循环返回的 $events
数组,添加 place_parent_X
元素,但我不确定如何实现这个。
I'm looking for the simplest way to recursively get all the parent elements from a database using the adjacency list / single table inheritance model (id, parent_id
).
My select currently looks like this:
$sql = "SELECT
e.id,
TIME_FORMAT(e.start_time, '%H:%i') AS start_time,
$title AS title,
$description AS description,
$type AS type,
$place_name AS place_name,
p.parent_id AS place_parent_id,
p.city AS place_city,
p.country AS place_country
FROM event AS e
LEFT JOIN place AS p ON p.id = e.place_id
LEFT JOIN event_type AS et ON et.id = e.event_type_id
WHERE e.day_id = '$day_id'
AND e.private_flag = 0
ORDER BY start_time";
Each event
is linked to a place
, and each place
can be a child of another place
(upto about 5 levels deep)
Is this possible in a single select with mysql?
At the moment I am thinking it could be a separate function which loops through the returned $events
array, adding place_parent_X
elements as it goes, but am not sure how to implement this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以在
MySQL
中执行此操作,但您需要创建一个函数并在查询中使用 in 。有关详细说明,请参阅我的博客中的此条目:
MySQL
中,以下是函数和查询:
后一个查询将选择给定节点的所有后代(您应该在
@start_with 变量)
要查找给定节点的所有祖先,您可以使用不带函数的简单查询:
我的博客中的这篇文章更详细地描述了此查询:
为了使这两种解决方案在合理的时间内发挥作用,您需要在两个
id< 上都有索引/code> 和
父级
。确保您的
id
被定义为PRIMARY KEY
并且您在parent
上有辅助索引。It's possible to do it in
MySQL
, but you'll need to create a function and use in in a query.See this entry in my blog for detailed explanations:
MySQL
Here are the function and the query:
The latter query will select all descendants of a given node (which you should set in the
@start_with
variable)To find all ancestors of a given node you can use a simple query without functions:
This article in my blog described this query in more detail:
For both these solutions to work in reasonable time, you need to have the indexes on both
id
andparent
.Make sure your
id
is defined as aPRIMARY KEY
and you have a seconday index onparent
.标准的父子数据库设计不可能做到这一点。
但是,您可以使用 嵌套集 方法并在一个查询,尽管这需要相当多的工作才能达到这一点。
It's not possible with the standard parent-child DB design.
However, you could use a nested set approach and do it in one query, though that will take quite a bit of work to get to that point.