MySQL:将VARCHAR转换为DECIMAL并在范围之间查找

时间:2015-04-01 10:45:50

标签: mysql

我在列

中有这样的数据
H1.1
H1.2
H1.3
H1.10
H50.1
H50.5
H55.5

我想在#1.10到#50.1之间进行搜索。我尝试了这样的查询,但我没有得到理想的结果。

SELECT p_code FROM table 
WHERE CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', 1),SIGNED INTEGER) between CONVERT(SUBSTRING_INDEX('1.1', '.', 1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX('1.99', '.', 1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', 1),SIGNED INTEGER) 
between CONVERT(SUBSTRING_INDEX('1.1', '.', -1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX('1.99', '.', -1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', 1),SIGNED INTEGER)>=CONVERT(SUBSTRING_INDEX('1.1', '.', 1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', 1),SIGNED INTEGER)<=CONVERT(SUBSTRING_INDEX('1.99', '.', 1),SIGNED INTEGER)
AND CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', -1),SIGNED INTEGER)>=CONVERT(SUBSTRING_INDEX('1.1', '.', -1),SIGNED INTEGER) 
AND CONVERT(SUBSTRING_INDEX(REPLACE(`code`,'H',''), '.', -1),SIGNED INTEGER)<=CONVERT(SUBSTRING_INDEX('1.99', '.', -1),SIGNED INTEGER)
ORDER BY LENGTH(`code`)  desc ,`code` desc

我也试过这个:

(CONVERT(REPLACE(`code`,'H',''),DECIMAL(5,3)) BETWEEN CONVERT('1.1',DECIMAL(5,3))
AND CONVERT('1.99',DECIMAL(5,3)))

1 个答案:

答案 0 :(得分:0)

您可以使用临时表格执行此操作:

CREATE TEMPORARY TABLE temp_table (
    code decimal(5,3)
);

INSERT INTO temp_table (code)
SELECT CONVERT(REPLACE(`code`,'H',''), DECIMAL(5,3))
FROM `table`;
SELECT code FROM temp_table WHERE code BETWEEN 1.10 AND 50.1;