单表子查询
好吧,我有一个表,
Tasks
--
TaskId (unique autoinc primary)
ChildOf (Contains task ID of parent, or 0 if top tier (no parent))
我需要编写一个查询来选择 ChildOf = 0 的所有记录...简单吧?
好的,但还需要返回另一列,其中的结果告诉每个任务有多少个子项...
所以结果看起来像这样...
TaskID ... ChildOf ... countChildren
37 ...... 0 .... 3
42 ...... 0 .... 0
99 ...... 0 .... 1
etc....
我知道我需要的两个查询是这样的,但需要以某种方式将它们组合起来...
Select TaskId as ParentTaskId, ChildOf from Tasks where ChildOf = 0
并且
Select count(TaskId) from Tasks where ChildOf = ParentTaskId
注意:只有 2 层...父母和孩子...没有孙子!所以希望这能让事情变得不那么复杂。
非常感谢任何帮助。感谢迄今为止所有的帮助!
Ok so I have a table
Tasks
--
TaskId (unique autoinc primary)
ChildOf (Contains task ID of parent, or 0 if top tier (no parent))
I need to write a query that selects all records with ChildOf = 0 ... Simple right ?
Ok but also need to have another column returned with the results that tells how many Children each Task has ...
So result would look like this ...
TaskID ... ChildOf ... countChildren
37 ...... 0 .... 3
42 ...... 0 .... 0
99 ...... 0 .... 1
etc....
I know the two queries I need are something like this, but need to combine them somehow...
Select TaskId as ParentTaskId, ChildOf from Tasks where ChildOf = 0
and
Select count(TaskId) from Tasks where ChildOf = ParentTaskId
NOTE: There are only 2 tiers.. Parent and Child ... No Grandchildren! So hopefully that makes it a bit less complicated.
Any help is greatly appreciated. Thanks for all the help so far!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的事情应该这样做:
Something like this should do it:
试试这个:
Try this: