如何在查询中执行查询并将其设置为主查询的条件
Org_table:
OrgName Id ParentID
Org1 20 Null
Org2 21 20
Org3 22 21
Org4 23 21
Org5 24 22
Org6 25 Null
上表中Org1是超级组织,Org2是Org1的子组织。 Org2 的子组织是 Org3 和 Org4。 Org 5 是 Org3 的子 Org,
我想在数据网格中的父 Org1 下显示这些 Org 的所有详细信息。这里我只知道Org1 ID 所以mysql查询就像
Select OrgName from Org_table where ID= 20 and ParentID is 20;
但是这个查询只返回Org1和Org2,我也必须返回Org3,Org4和Org5,因为它在Org1下。我该怎么办呢。我应该使用某种循环,如果可以的话该怎么做。我正在使用 c# 在我的 asp.net 网站中执行此操作。
在运行时我不会知道哪个组织是哪个组织的子组织。所以我必须找到如果父ID位于主组织下
我想做递归查询
Org_table:
OrgName Id ParentID
Org1 20 Null
Org2 21 20
Org3 22 21
Org4 23 21
Org5 24 22
Org6 25 Null
In the table above Org1 is the super organisation and Org2 is the child of Org1. And Sub Org of Org2 is Org3 and Org4. and Org 5 is sub Org of Org3
I want to display all the details of these Org under the parent Org1 in my data grid. Here I know only the Org1 ID
so mysql query is like
Select OrgName from Org_table where ID= 20 and ParentID is 20;
But this query returns only Org1 and Org2, I have to return Org3, Org4 and Org5 also because it is under Org1. How can I do it. should I use some kind of loop if so how to do it. I am using c# do this is in my asp.net website.
During runtime I wont know which org is child of which ORg. SO I have to find the If the parent id is under the main Org
I want to do recursive query
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我手头没有 mysql,但这应该可以满足您的需要
不确定更新语句上的语法对于 mysql 是否完全正确..可能需要稍微调整一下。
I don't have mysql on hand, but this should do what you need
Not sure if the syntax on the update statement is entirely correct for mysql.. might need to be tweeked a little.
您可以迭代结果并继续询问下一个相关记录。
首先运行
,然后对于 Id != 为 20 的每个结果,您应该再次运行查询。
(Org2 的示例)
您可以将结果保留在列表中,然后获取不同值。
You can iterate on the results and keep asking for the next related records.
First you run
And then for each result that has an Id != of 20 you should run the query again.
(Example for Org2)
You can keep the results on a list an then obtain the distincts.
由于 MySQL 不支持递归查询/CTE,因此您必须对其进行模拟(这并不简单)。
这是关于该主题的优秀教程:
http://explainextend.com/ 2009/03/17/hierarchical-queries-in-mysql/
出于礼貌,我不会在这里复制代码:)
Since MySQL does not support recursive queries/CTEs, you will have to emulate that (which is not, say, straightforward).
Here's an excellent tutorial on the subject:
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/
I will have the decency of not copying the code here :)