我想将英尺和英寸转换为厘米格式
我的数据库中的格式为:
4' 6" (4英尺6英寸)
转换为厘米的公式
4*30.48 = 121.92 (convert feet to centimeters = multiply by 30.48)
6*2.54 = 15.24 (convert inches to centimeters = multiply by 2.54)
So Result = 121.92 + 15.24 = 137.16 cm
例如:
实际表格:英寸
SELECT * FROM inches
id height
1 4'6"
2 4'7"
3 5'8"
4 5'9"
当我进行SQL查询时,我希望以下结果为厘米
id height
1 137.16
2 139.7
3 172.72
4 175.26
提前致谢:)
答案 0 :(得分:3)
在应用程序级别上可能要容易得多,但是如果你真的不得不这样做,你可以在SQL中使用SUBSTR
和INSTR
函数以及一些基本的数学运算:< / p>
SET @height = '4''6"';
SELECT
SUBSTR(@height, 1, INSTR(@height, '''') - 1) * 12 * 2.54 +
SUBSTR(@height, INSTR(@height, '''') + 1, INSTR(@height, '"') - INSTR(@height, '''') - 1) * 2.54;
-- yields 137.16
或者,应用于您的表结构:
SELECT id,
SUBSTR(height, 1, INSTR(height, '''') - 1) * 12 * 2.54 +
SUBSTR(height, INSTR(height, '''') + 1, INSTR(height, '"') - INSTR(height, '''') - 1) * 2.54 AS height
FROM inches;
答案 1 :(得分:2)
应用程序端进程会更好,
然而,
SELECT
(CAST(SUBSTR(height,1, LOCATE("'",height)-1) AS UNSIGNED) * 30.48) +
(CAST(SUBSTR(height, LOCATE("'",height)+1) AS UNSIGNED) * 2.54 ) AS cm
FROM
inches;