用于选择父名称和子名称的 SQL 查询
我有一个具有以下结构的表 -
Category {Id, Name, ParentId}
我有这样的值 -
id name parentid
-------------------------------
1 Technology Focus NULL
2 Tools 1
3 Database 1
如何编写显示如下的查询 -
name (parent) name (child)
--------------------------------
Technology Focus Tools
Technology Focus Database
etc..
我相信我需要使用 Group By 子句,但我不太明白。
I have a table with the following structure -
Category {Id, Name, ParentId}
I have values like this -
id name parentid
-------------------------------
1 Technology Focus NULL
2 Tools 1
3 Database 1
How do I write a query that displays like this -
name (parent) name (child)
--------------------------------
Technology Focus Tools
Technology Focus Database
etc..
I believe I need to use the Group By clause but I'm not quite getting it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我没看错的话,我想你只需要
if i'm looking at that correctly, i think you just need
您需要像这样将表本身连接起来:
You need to join the table on itself like this:
如果您尝试在 SQL 中实现树状结构,那么这有点错误。
您应该使用两个表来实现树:
这种结构(称为闭包表)更易于维护(预制更新、重新排列结构等)。
然后您选择如下数据:
无论如何,请阅读闭包表,你就会明白为什么..
If you are trying to implement at tree-like structure in SQL, then this, kinda, is the wrong way to do this.
You should use two tables to implement a tree:
This structure (know as Closure Table )is easier to maintain (preform updates, rearrange structure , etc. ).
Then you select the data like:
Anyway , read about Closure Tables, you will understand why ..