MySQL 将高度格式从厘米转换为英尺英寸?

MySQL convert height format from centimeters to feet-inches?

我的数据库中的格式是:以厘米为单位,例如 137 cm

我想将 137 厘米之类的示例转换为 4'6"(4 英尺 6 英寸)

实际Table:身高厘米

例如:

SELECT * FROM height

id height_cm
1  137
2  139
3  172
4  175

当我执行 SQL 查询

时,我希望得到以下结果(英尺-英寸)
id height_finc
1  4'6"
2  4'7"
3  5'8"
4  5'9"

公式为:1 inch = 2.54 cm1 foot = 12 inches

这基本上是算术和字符串格式:

select floor(height_cm / (2.54 * 12)) as feet,
       (height_cm - floor(height_cm / (2.54 * 12)) * 12 * 2.54) / 2.54 as inches

要格式化为字符串:

select concat(floor(height_cm / (2.54 * 12)), '''', 
              round((height_cm - floor(height_cm / (2.54 * 12)) * 12 * 2.54) / 2.54), '"') as feet_inches

我认为这更简单:

select concat(floor(height_cm / (2.54 * 12)), '''', 
              round(height_cm / 2.54) % 12, '"')

你需要在做select的时候做一些算术运算。

让我们开始获取 inchfoot

mysql> select id, 
floor(height_cm/(12*2.54)) as foot , 
round((height_cm mod (12*2.54))/2.54) as inch from height ;
+------+------+------+
| id   | foot | inch |
+------+------+------+
|    1 |    4 |    6 |
|    2 |    4 |    7 |
|    3 |    5 |    8 |
|    4 |    5 |    9 |
+------+------+------+

现在使用concat我们可以格式化显示

mysql> select id, 
concat(
 floor(height_cm/(12*2.54))
 ,'\''
 ,round((height_cm mod (12*2.54))/2.54)
 ,'"'
) as height_finc from height ;
+------+-------------+
| id   | height_finc |
+------+-------------+
|    1 | 4'6"        |
|    2 | 4'7"        |
|    3 | 5'8"        |
|    4 | 5'9"        |
+------+-------------+