SQL Server:如何选择第二高的parentid?
我有一个包含以下页面的 SQL Server 数据库:
+------------+--------------+-------------------------------+ | pageid | parentid | title | +------------+--------------+-------------------------------+ | 1 | null | Home | +------------+--------------+-------------------------------+ | 2 | 1 | News | +------------+--------------+-------------------------------+ | 3 | 1 | User | +------------+--------------+-------------------------------+ | 4 | 3 | Edit profile | +------------+--------------+-------------------------------+ | 5 | 3 | Messages | +------------+--------------+-------------------------------+ | 6 | 5 | View all | +------------+--------------+-------------------------------+
如何为任何行选择第二高(级别)的父 ID?因此,对于 pageid=6(查看全部),它应该返回parentid->3(用户)。
I have a SQL Server database with these pages:
+------------+--------------+-------------------------------+ | pageid | parentid | title | +------------+--------------+-------------------------------+ | 1 | null | Home | +------------+--------------+-------------------------------+ | 2 | 1 | News | +------------+--------------+-------------------------------+ | 3 | 1 | User | +------------+--------------+-------------------------------+ | 4 | 3 | Edit profile | +------------+--------------+-------------------------------+ | 5 | 3 | Messages | +------------+--------------+-------------------------------+ | 6 | 5 | View all | +------------+--------------+-------------------------------+
How do I select the second-highest (in level) parentid for any row? So for pageid=6 (View all) it should return parentid->3 (User).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于父层次结构中固定且已知的步骤数,请使用显式联接:
对于层次结构中未知的步骤数,请使用递归 cte,但您需要停止条件,请参阅 使用公用表表达式的递归查询。
For a fixed and known number of steps up the parent hierachy, use explicit joins:
For an unknow number of steps in the hierachy, use a recursive cte, but you need a stop criteria, see Recursive Queries Using Common Table Expressions.
尝试:
我无法从您的问题和示例中选择您是否需要 pageid 或 Parentid。
Try:
I couldn't pick from your question and your sample whether you want pageid or parentid.