按多列排序行选择
我有一个数据库
id | parentid | name
1 | 0 | CatOne
2 | 0 | CatTwo
3 | 0 | CatThree
4 | 1 | SubCatOne
5 | 1 | SubCatOne2
6 | 3 | SubCatThree
如何选择这只猫 Order By id
, parentid
?那是
CatOne 1
--SubCatOne 4
--SubCatOne2 5
CatTwo 2
CatThree 3
--SubCatThree 6
I have a database
id | parentid | name
1 | 0 | CatOne
2 | 0 | CatTwo
3 | 0 | CatThree
4 | 1 | SubCatOne
5 | 1 | SubCatOne2
6 | 3 | SubCatThree
How I can select this cats Order By id
, parentid
? That is
CatOne 1
--SubCatOne 4
--SubCatOne2 5
CatTwo 2
CatThree 3
--SubCatThree 6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您的表名为 cats,请尝试以下操作:
更新以包括与子项相比,父项具有更高的 id
assuming your table is named cats, try this:
Updated to include when parent would have higher id compared to the children
这应该可以做到...除了名称的双破折号“--”前缀...
按第一个情况/何时的顺序将所有属于顶级的项目或按主要级别的次要级别ID。因此,如果您有超过 1000 个条目,尝试使用提供的父 * 1000 个示例 hack 不会有问题。第二个 case/when 将在父 ID = 0 时强制到其分组列表的顶部及其下方的所有子条目,但在下一个父 ID 之前。
但是,如果您确实想要双破折号,请更改为
This should do it... with exception of a double dash "--" prefix to the name...
The order by FIRST case/when puts all the items that ARE the top level, or at the secondary level by the primary level's ID. So trying to use a parent * 1000 sample hack offered won't be an issue if you have over 1000 entries. The SECOND case/when will then force when the parent ID = 0 to the TOP of its grouped list and all its subsidiary entries UNDER it, but before the next parent ID.
however, if you DO want the double dash, change to
如果您要按以下方式排序: ORDER BY Parentid, id
那么您将得到您正在寻找的顺序,但它不会是有意的或任何东西,就像您的示例一样。
SQL 可能不是执行此类缩进组的最佳媒介。你可以......但最好在前端应用程序
编辑中完成:抱歉误读问题,Eric Petroelje 所说的。
编辑编辑:或者从表中选择,连接回自身(一个用于 Cat,一个用于 SubCat),然后指定不同的顺序,每个表一个。
If you were to sort by: ORDER BY parentid, id
then you would get the order you are looking for, but it wouldn't be intended or anything, like your example.
SQL is probably not the best medium for doing indented group like that. You can...but it's better done in your front end app
edit: sorry misread question, what Eric Petroelje said.
edit edit: Or select from the table, joined back to itself, (one for the Cat and one for the SubCat) and then specify the different ordering, one from each table.
这:
返回:
This:
Returns:
你可以试试这个。它不完全是您指定的格式,但它符合您的要求吗?
它产生以下内容:
You could try this. It is not exactly the format you specify but does it match what you require?
It produces the following: