我有一个MySQL表(简化)的以下模式,它有一个封装了层次结构的索引字段 整个评论主题中的评论条目。
+----------+------------+-----+---------+----------------+
| id | INTEGER | PRI | NULL | auto_increment |
| comment | TEXT | | NULL | |
| index | TEXT | | NULL | |
+----------+------------+-----+---------+----------------+
id: comment: index:
-------------------------------------------------------
1 Rootentry1 1
2 Answer1 on Rootentry1 1.1
3 Rootentry2 2
4 Answer1 on Answer1 on Rootentry1 1.1.1
5 Rootentry3 3
6 Answer1 on Rootentry2 2.1
7 Answer2 on Rootentry1 1.2
现在我想以最先出现Rootentry
的方式对表格进行排序。
结果应按以下顺序排列:
id: comment: index:
------------------------------------------------------
5 Rootentry3 3
3 Rootentry2 2
6 Answer1 on Rootentry2 2.1
1 Rootentry1 1
2 Answer1 on Rootentry1 1.1
4 Answer1 on Answer1 on Rootentry1 1.1.1
7 Answer2 on Rootentry1 1.2
我需要一种排序算法,以降序方式对第一个索引进行排序,并按升序方式对以下字符进行排序 对这样的条目进行排序的声明是什么?
答案 0 :(得分:0)
applicationDidBecomeActive
输出:
select
*
from table1
order by
cast(substring_index(`index`, '.', 1) as unsigned) desc,
substring(`index`, 2+length(substring_index(`index`, '.', 1))) asc
答案 1 :(得分:0)
只是为了好玩......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,legal VARCHAR(12) NOT NULL UNIQUE);
INSERT INTO my_table (legal) VALUES ('1'),('1.1'),('2'),('1.1.1'),('3'),('2.1'),('1.2');
SELECT * FROM my_table;
+----+-------+
| id | legal |
+----+-------+
| 1 | 1 |
| 2 | 1.1 |
| 4 | 1.1.1 |
| 7 | 1.2 |
| 3 | 2 |
| 6 | 2.1 |
| 5 | 3 |
+----+-------+
SELECT *
, FLOOR(INET_ATON(RPAD(legal,5,'.0'))/16000000) x -- or perhaps 16777216
FROM my_table
ORDER
BY x DESC
, legal;
+----+-------+------+
| id | legal | x |
+----+-------+------+
| 5 | 3 | 3 |
| 3 | 2 | 2 |
| 6 | 2.1 | 2 |
| 1 | 1 | 1 |
| 2 | 1.1 | 1 |
| 4 | 1.1.1 | 1 |
| 7 | 1.2 | 1 |
+----+-------+------+