SQL Order By 查询问题
我有一个包含以下数据集的表,
id name parent
------------------
1 xyz NULL
2 def NULL
3 mno abc
4 abc NULL
5 pqr abc
6 qfx def
我希望按以下顺序获取数据:
1 abc NULL
3 mno abc
5 pqr abc
2 def NULL
6 qfx def
4 xyz NULL
我的意思是必须按用户名进行排序,但具有相同父级的记录必须一起显示,并且位于父级记录的下方。
我正在使用MySQL。
I have a table with following dataset
id name parent
------------------
1 xyz NULL
2 def NULL
3 mno abc
4 abc NULL
5 pqr abc
6 qfx def
I would want to fetch the data in the following order:
1 abc NULL
3 mno abc
5 pqr abc
2 def NULL
6 qfx def
4 xyz NULL
What I mean is ORDERing has to occur by Username but records with same parent must show together and just below the record for the parent.
I am using MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试这个新答案:
它连接了两个字符串,因此它的顺序应该如下所示:
try this new answer:
it concatenated the two strings so it should order like this:
像这样的东西(不一定完全这样):
我实际上会尝试用不太可能出现在名称中的字符替换
'.'
。Something like this (not necessarily exactly like this):
I would actually try to replace
'.'
with a character that is unlikely to appear in the names.使用以下查询:
Use the below query:
这根本不是问题吗?抓住它:
it's not a problem at all? catch it:
你遇到的最大问题是你想要两个截然不同的方面。您希望它按用户名顺序排列,但如果有匹配的父项,您希望将其分组。
最明显的是
但这仍然首先按父级排序。
我确信有可能得到你想要的东西,但是,我还没有喝咖啡来制定一个简单的完整解决方案。
The biggest problem you have is you want 2 rather different aspects. You want it in username order, but if there is a matching parent you want to group it.
The most obvious would be
But that still sorts it by parent first.
Im sure its possible to get exactly what you wanted, but, I havent had the caffine yet to work out an easy full solution.
在 Oracle 中,我发现有必要编写存储过程来进行分层排序。一些 RDBMS 提供 CTE(通用表表达式),可以达到相同的结果。我不熟悉 mySql,也不知道它有什么支持,但以下内容可能会有所帮助。
维基百科文章
mySql 特定
另外 Google“Joe Celko 树和层次结构”
Other in Oracle I have found it necessary to write Stored Proc to do hierarchical ordering. Some RDBMSes offer CTE (common table expressions) which can acheive the same result. I am not familiar with mySql and don't know what support it has but the following may help.
Wikipedia article
mySql specific
Also Google "Joe Celko Trees and Hierarchies"