【问题标题】:sql- Like Query findsql-like 查询查找
【发布时间】:2011-07-08 15:31:44
【问题描述】:

有人知道该怎么做吗?我正在做一个类似的查询来选择信息。示例:

SELECT * 
  FROM customers
 WHERE customer_name LIKE '26%' 

将返回

26_xx
26_xx
265_xx

但我只想显示 26_xx

我已经尝试过来自网站的建议:

SELECT * 
  FROM customers
 WHERE customer_name LIKE 'H%!%' escape '!';

但那也返回了

26_xx
26_xx
265_xx

【问题讨论】:

  • 什么数据库,什么版本?
  • and SELECT * FROM customers WHERE customer_name = '26_xx' 不好吗?
  • 我怀疑这是正则表达式问题?
  • 您想如何确定要显示的结果?

标签: sql


【解决方案1】:

在 T-SQL 中,您可以使用 [] 转义 通配符 字符 _;

SELECT * FROM customers
    WHERE customer_name LIKE '26[_]%'

ESCAPE 版本是;

SELECT * FROM customers
    WHERE customer_name LIKE '26!_%' ESCAPE '!'

【讨论】:

  • 你不必逃避“_”,对吗?至少在我的系统(SQL 2008 R2)上,你可以说 LIKE '26_%'
  • _任何字符,因此与265_xx 中的5 匹配
  • 这不太对;它在我下面的示例数据集中返回“26-22”(我没有注意到,真丢脸),但不是“265_22”。无论如何,我已经在下面更正了我的答案;感谢您的提示。
  • 我认为那是因为您限制为 5 个字符,所以它不适合匹配
【解决方案2】:
SELECT * 

FROM customers

WHERE customer_name LIKE '26_%'

这是你的意思吗?只有名字以“26_”开头的地方,还是我读错了你的问题?

【讨论】:

    【解决方案3】:

    这应该可行:

    SELECT * 
    FROM customers
    WHERE customer_name LIKE '26[_]%' 
      and len(customer_name) = 5
    

    证明:

    select
      sample_data.*
    from
      (
      select '26_55' as customer_name
      union
      select '26_abc'
      union
      select '265_22'
      union
      select '26-22'
      union
      select 'abc'
      union
      select '26_18'
      ) sample_data
    where sample_data.customer_name like '26[_]%'
      and len(sample_data.customer_name) = 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-15
      • 2018-09-18
      • 2017-08-15
      • 1970-01-01
      • 2021-04-12
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多