我试图按字符串上的某个字符排序,例如,
之前:
+----+---------+
| id | name |
+----+---------+
| 1 | red |
| 2 | red-a |
| 3 | red-xy |
| 4 | blue |
| 5 | blue-a |
| 6 | blue-xy |
+----+---------+
后:
+----+---------+
| id | name |
+----+---------+
| 4 | blue |
| 1 | red |
| 5 | blue-a |
| 2 | red-a |
| 6 | blue-xy |
| 3 | red-xy |
+----+---------+
是否有任何方法可以使用ORDER BY
提前谢谢。
答案 0 :(得分:1)
SELECT
CASE
WHEN RIGHT(`name`,LENGTH(`name`)-INSTR(`name`,'-')) = `name` THEN ''
ELSE RIGHT(`name`,LENGTH(`name`)-INSTR(`name`,'-'))
END AS `suffix`,
`name`
FROM
`table1`
ORDER BY
`suffix`, `name`
如果未找到后缀,则会将记录放在第一行中。 警告:第一个破折号用于将单词与前缀分开。
答案 1 :(得分:1)
这将满足您的需求。如果你有很多行,不愿意承诺表现出色:
select id, name from
(
select id,
name,
if (substring_index(name,'-', -1) = name, '', substring_index(name,'-', -1)) as grouping
from Table1
order by grouping, name
) as subTable
[编辑]实际上,可以通过以下方式将其简化为单个选择:
select id,
name
from Table1
order by if (substring_index(name,'-', -1) = name, '', substring_index(name,'-', -1)), name
答案 2 :(得分:1)
这些查询更具可读性,这可能是对后缀进行排序的最简单方法
SELECT
*
, IF (LOCATE('-', name) = 0
, 0
, LENGTH(SUBSTRING_INDEX(name, '-', -1))
)
suffix_length
FROM
Table1
ORDER BY
suffix_length
;
SELECT
*
FROM
Table1
ORDER BY
IF (LOCATE('-', name) = 0
, 0
, LENGTH(SUBSTRING_INDEX(name, '-', -1))
)
;