【问题标题】:Strip word from mysql value从 mysql 值中删除单词
【发布时间】:2020-07-02 10:59:29
【问题描述】:

希望运行选择查询以按尺寸过滤产品,但 Product_Size 列在数字后有字符,例如“英寸”。我尝试了以下方法,但没有返回任何结果。

SELECT * FROM `products` where Product_size BETWEEN '2 inches' AND '4.9 inches'

如何从查询中去掉“英寸”这个词?

【问题讨论】:

  • Product_size列的数据类型是什么?
  • @forpas - varchar(255)
  • 字符串之间的任何比较总是按字母顺序进行。发布示例数据。

标签: php mysql select


【解决方案1】:

您可以使用replace()

  SELECT * FROM products 
  where Category_List =1 and Category_List_2=7 and 
  Designed_For_Who LIKE '%%' and (RRP between '0' and '100000') and 
  Product_size BETWEEN cast(replace('2 inches',' inches','') as int) AND 
  cast(replace('4.9 inches',' inches','') as int) 
  ORDER BY Name ASC

【讨论】:

  • 谢谢,但是当我将其添加到我的查询中(如下)时,我得到了一个错误? `SELECT * FROM products where Category_List =1 and Category_List_2=7 and created_For_Who LIKE '%%' and (RRP between '0' and '100000') and Product_size BETWEEN cast(replace('2 inches',' inches','' ) as int) AND cast(replace('4.9 inches','inches','') as int ORDER BY Name ASC
  • 您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在“ORDER BY Name ASC LIMIT 0, 25”附近使用的正确语法
  • @Designer,您错过了一个括号 - SELECT * FROM products where Category_List =1 and Category_List_2=7 and created_For_Who LIKE '%%' and (RRP between '0' and '100000') and Product_size BETWEEN cast(replace('2 英寸','inches','') as int) AND cast(replace('4.9 inches','inches','') as int) ORDER BY Name ASC
【解决方案2】:

您必须将字符串转换为数值。
对于您的情况,可以通过添加 0 隐式完成此转换:

SELECT * 
FROM `products` 
WHERE 
  Product_size LIKE '%inches'
  AND
  Product_size + 0 BETWEEN '2 inches' + 0 AND '4.9 inches' + 0

查看简化的demo

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多