限制字符串值之间的SQL

时间:2017-10-10 10:06:02

标签: java mysql sql

我想要一个sql以这样的方式工作:如果我在's1'到's3'之间输入它不应该在包含结果中给我's',因为'10'不在'1'和'3之间“

我的创建声明:

CREATE TABLE food_name
    (`food_name` varchar(4))
;

我的插入声明:

INSERT INTO food_name
    (`food_name`)
VALUES
    ('s1'),
    ('s2'),
    ('s3'),
    ('s10'),
    ('ssss'),
('Tee'),
('Pee')
;

我的选择陈述:

SELECT * 
FROM   food_name
WHERE BINARY food_name between 's1' and 's3';

3 个答案:

答案 0 :(得分:1)

这应该可以解决问题 SELECT * FROM food_name WHERE BINARY food_name between 's1' and 's3' AND ( (food_name NOT LIKE 's%') OR ( concat('',SUBSTR(food_name, 2) * 1) = SUBSTR(food_name, 2) -- is 's' + number AND SUBSTR(food_name, 2) BETWEEN 1 AND 3 ) ); http://www.sqlfiddle.com/#!9/c72c18/41/0

更新:在第二个想法,这有点检测到参数内的数字的出现。 http://www.sqlfiddle.com/#!9/c72c18/71/2

SET @FROM_STR = 's1';
SET @TO_STR = 's3';

SELECT * 
FROM   food_name
JOIN (
  SELECT 
  CASE WHEN concat('',SUBSTR(@FROM_STR, 2) * 1) = SUBSTR(@FROM_STR, 2) THEN
    CAST(SUBSTR(@FROM_STR, 2) AS SIGNED)
  ELSE
    NULL
  END
  AS FROM_NUM,  
  CASE WHEN concat('',SUBSTR(@TO_STR, 2) * 1) = SUBSTR(@TO_STR, 2) THEN
    CAST(SUBSTR(@TO_STR, 2) AS SIGNED)
  ELSE
    NULL
  END
  AS TO_NUM

  FROM DUAL
     ) PARAMS
WHERE BINARY food_name between @FROM_STR and @TO_STR AND (
  (food_name NOT LIKE 's%') OR 
  (
    concat('',SUBSTR(food_name, 2) * 1) = SUBSTR(food_name, 2) -- is 's' + number
    AND
    CAST(SUBSTR(food_name, 2) AS SIGNED) BETWEEN PARAMS.FROM_NUM AND PARAMS.TO_NUM
  )
);

答案 1 :(得分:0)

您可以使用SUBSTRINGCAST

SELECT *
FROM   food_name
WHERE cast(substr(a_food_name, 2, length(a_food_name)) as UNSIGNED) between 1 and 3;

demo

我已重命名您的属性,因为它是bad habit,可以为数据库中的其他对象指定相同的名称。

答案 2 :(得分:0)

戴维德但更短:

SELECT * 
FROM   food_name
WHERE SUBSTR(food_name, 2)  between 1 and 3