zoukankan      html  css  js  c++  java
  • PostgreSQL 匹配字符串前缀

    需求:

    假设数据库表中,记录如下:

     prefix | name | shortname | status 
    --------+------+-----------+--------
     abcdef | test | test      | S
     abc    | test | test      | S
     ab     | test | test      | S
     a      | test | test      | S

    给定字符串”abcdefghjk”,如何匹配到最长的那条记录?

    方案:

    在github找到个extension,省去很多麻烦,查看具体信息,请 猛戳这里

    测试:

    • 安装
      sudo apt-get install postgresql-9.5-prefix
      psql
      create extension prefix;
    • 数据准备
      create table prefixes (
             prefix    prefix_range primary key,
             name      text not null,
             shortname text,
             status    char default 'S',
      
             check( status in ('S', 'R') )
      );
      insert into prefixes select 'abcdf','test','test','S';
      insert into prefixes select 'abcdef','test','test','S';
      insert into prefixes select 'abc','test','test','S';
      insert into prefixes select 'ab','test','test','S';
      insert into prefixes select 'a','test','test','S';
    • 测试
      test=# select * from prefixes where prefix @> 'abcdefgh' ORDER BY length(prefix) DESC;
       prefix | name | shortname | status 
      --------+------+-----------+--------
       abcdef | test | test      | S
       abc    | test | test      | S
       ab     | test | test      | S
       a      | test | test      | S
      (4 rows)

    只要在加上limit 1,即可得到最长的匹配值了。对于数据量大的表还可以建立索引,具体参见github

  • 相关阅读:
    Win32 DPAPI加密编程
    .NET环境下的DPAPI加密编程
    Windows加密API的功能分类
    Windows加密API的层次
    Windows加密服务架构
    简单H5单页面真机调试
    vue中使用动画vue-particles
    particular.js
    sublime快捷键
    判断内核
  • 原文地址:https://www.cnblogs.com/cxy486/p/5365750.html
Copyright © 2011-2022 走看看