【问题标题】:pattern matching using "LIKE" in query ,postgres在查询中使用“LIKE”进行模式匹配,postgres
【发布时间】:2013-07-19 08:08:55
【问题描述】:

如何使用“LIKE”来查找字符串中包含例如“R011”、“R012”、“R021”、“R022”的行?我不想选择“R01”或“R02”。

SELECT 'Code'
FROM "public"."Test"
WHERE 'Code' LIKE 'R01%';

在“代码”列中名为“测试”的表中,我使用了上面的查询,但结果是:

no rows found.

行如下:

R(01-04,11)  Personnel professionnel des
R01  M้decins, dentistes et v้t้r.
R011 M้decins sp้cialistes
R022 Omnipraticiens et m้decins en m้decine

【问题讨论】:

    标签: postgresql sql-like


    【解决方案1】:
    SELECT *
    FROM   public."Test"
    WHERE  "Code" LIKE 'R0__';
    

    这需要'R0' 之后的 2 个字符。

    您使用单引号没有任何意义。从阅读identifiers and key words in the manual 开始。我的建议:根本不要使用大小写混合的标识符。
    然后前往information about pattern matching

    更具体地说,您可以使用如下正则表达式:

    WHERE  "Code" ~ '^R0\d\d$';  -- allowing any 2 digits
    

    甚至:

    WHERE  "Code" ~ '^R0[12]{2}$';  -- allowing only 1 and 2
    

    【讨论】:

      【解决方案2】:

      您想使用下划线而不是百分比字符。下划线_ 匹配单个字符,其中百分比% 匹配零个或多个字符。

      select 'R011' like 'R01_'
      # true
      
      select 'R01' like 'R01_'
      # false
      

      或者更好的是,您可以使用正则表达式来匹配十进制字符。

      select 'R011' ~ 'R\\d{3}'
      

      http://www.postgresql.org/docs/9.2/static/functions-matching.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多