这在 SQL 中可能吗?
假设我有一个名为“species”的表,其中包含 3 列:“Id”、“ancestorId”和“name”。 'ancestorId' 是祖先物种的 'Id',因此,例如,如果智人的祖先是南方古猿,而南方古猿的 'Id' 是 5,那么智人的 'ancestorId' 就是 5。我们还可以说,有一种名为“第一个货币”的货币,其“Id”为 0 或 null。所以我想要的是从特定物种(例如智人)中选择一个祖先列表到“第一个物种”,无论途中有多少个节点。这可以用 SQL 实现吗?
Let's say I have a table called 'species' with 3 columns: 'Id', 'ancestorId' and 'name'. The 'ancestorId' is the 'Id' of the ancestor specie, so for example if the ancestor of the homo sapiens is the australopithecus, and australopithecus's 'Id' is 5, then homo sapiens's 'ancestorId' is 5. Let's say, also, that there is a specie called 'First specie' whose 'Id' is either 0 or null. So what I want is to select a list of ancestors from a particular specie, say, homo sapiens, to the 'First specie', no matter how many nodes are on the way. Is this possible with SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您很可能不想让您的第一个物种的 ID 为 null。 null 与 0 有很大不同。null 意味着你不知道该值是什么。 0 表示值为 0。注意 null <> null 且 0 = 0。这可能会影响您搜索识别第一个物种的方式。
You most likely don't want to make your first specie have an ID of null. null is very different from 0. null means you don't know what the value is. 0 means the value is 0. Note that null <> null and 0 = 0. This can affect how you search for an recognize the firt specie.
是的,我可以用 SQL 实现。您可以为此目的使用递归查询。请查看此处。阅读整页。
编辑
这适用于 ORACLE、SQL Server、PostgreSQL 以及任何其他具有递归查询支持的数据库。要处理不支持递归查询的数据库,您将不得不使用嵌套集模型。
Yeah, it i possible in SQL. You can use recursive queries for that purpose. Take a look at here. Read the full page.
Edit
This will work with ORACLE, SQL Server, PostgreSQL and with any other database that has recursive query support. To deal with the databases that don't support recursive queries, you will have to use the nested set model.
在 MySQL 中管理分层数据 是一个很好的资源,适合您的需求正在谈论,特别是如果您正在使用不支持递归查询的数据库系统。它讨论了您需要如何构建数据以便更轻松地完成您想做的事情。
Managing Hierarchical Data in MySQL is a good resource for what you're talking about, particularly if you're working with a database system that doesn't have recursive query support. It discusses how you'll need to structure your data in order to do what you want to more easily.
ANSI 方式是使用递归WITH 子句:
支持以下版本:
Oracle 从 v2 开始就支持分层查询,使用
CONNECT BY
语法。The ANSI way is to use a recursive WITH clause:
Supported by:
Oracle's had hierarchical query support since v2, using
CONNECT BY
syntax.