在MySQL中订购列

时间:2018-06-07 17:17:06

标签: mysql

我有一张表products,尺寸如下:

+------------+--------+-------+--------+
| product_id | length | width | height |
+------------+--------+-------+--------+
|          1 |  23.00 | 25.00 |  22.00 |
|          2 |  14.25 | 14.25 |   1.75 |
|          3 |  19.50 |  3.00 |   2.50 |
|          4 |   3.50 | 11.00 |  19.00 |
+------------+--------+-------+--------+

我需要做的是将它们整理好,因此length始终是最大的维度,width是第二大,height是最小的。这很容易:

SELECT
    GREATEST(length,width,height) AS length,
    LEAST(length,width,height) AS height
FROM products

但我怎样才能最终维度?然后我尝试了这个:

SELECT product_id,
    SUBSTRING_INDEX(GROUP_CONCAT(dim ORDER BY dim DESC), ',', 1) AS length,
    SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(dim ORDER BY dim DESC), ',', 2), ',', -1) AS width,
    SUBSTRING_INDEX(GROUP_CONCAT(dim ORDER BY dim DESC), ',', -1) AS height 
FROM
(
    SELECT product_id, length AS dim
    FROM products
    UNION
    SELECT product_id, width AS dim
    FROM products
    UNION
    SELECT product_id, height AS dim
    FROM products
) v
GROUP BY product_id;

这实际上有效,但看起来很荒谬。任何人都可以建议一个比我上面概述的更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

一些简单的数学运算会做到这一点,因为只有3列:

SELECT length + width + height 
     - GREATEST(length, width, height) 
     - LEAST(length, width, height) AS width
FROM products

对于超过一组固定的列,您基本上是不进行旋转,然后进行旋转。有些数据库有一个非标准的扩展名,比如T-SQL中的UNPIVOT / PIVOT,但我不是很容易在MySQL中做到这一点,它看起来不像你的查询,或者在使用listagg时在道德上等同。