在MYSQL中按英寸值排序

时间:2014-11-15 13:20:27

标签: mysql sql-order-by

我已经找到了答案,但无法解决这个问题。我想我已经结束但请你帮忙。

我有以下mysql查询:

SELECT `size` 
FROM `table` 
GROUP BY `size` 
ORDER BY CONVERT(SUBSTR(size, 1, POSITION('/' IN size) - 1), UNSIGNED INTEGER) ASC,
SUBSTRING_INDEX(size,'/',1)/SUBSTRING_INDEX(size,'/',-1) ASC

运行此结果会产生以下结果:

1"
2"
4"
3"
1/2"
3/8"
3/4"
11/4"
11/2"
21/2"

我需要将尺寸从最小到最大。对此的任何帮助都将受到广泛赞赏。谢谢。

注意,我也尝试删除"从数据库中的大小和结果完全相同。

数据集的一个示例:

1 1/2"
1 1/4"
1"
1/2"
1/4"
1/8"
10"
11/2"
11/4"
11/4""
12"
14"
16"
2 1/2"
2"
21/2"
3"
3/4"
3/8"
4"
5"
6"
8"

2 个答案:

答案 0 :(得分:1)

可爱的数据格式。我想你将不得不做分工。计算如下:

order by (case when size like '%/%'
               then (substring_index(size, '/', 1) + 0) / (substring_index(size, '/', 2) + 0)
               else size + 0
          end)

即使"是该字段的一部分,这仍然有效。 + 0执行“无声”转换。也就是说,它将字符串转换为第一个非数字字符。

编辑:

如果您可以先包含整数的空格,那么您可以这样做:

order by (case when size like '% %/%'
               then (substring_index(size, 1, ' ') + 0) +
                    ((substring_index(substring_index(size, ' ', 2), '/', 1) + 0) /
                     (substring_index(size, '/', -1) + 0)
                    )
               when size like '%/%'
               then (substring_index(size, '/', 1) + 0) / (substring_index(size, '/', 2) + 0)
               else size + 0
          end)

答案 1 :(得分:0)

你查询几乎工作。但是,在顺序的第一部分,你应该从字符串长度中减去位置。

SELECT `size`
FROM `size` 
GROUP BY `size` 
ORDER BY CONVERT(SUBSTR(size, 1, LENGTH(size) - POSITION('/' IN size) - 1), UNSIGNED INTEGER) ASC,
SUBSTRING_INDEX(size,'/',1)/SUBSTRING_INDEX(size,'/',-1) ASC

http://sqlfiddle.com/#!2/cd0658/6