【问题标题】:Postgres SELECT statement where field value ends with字段值以结尾的 Postgres SELECT 语句
【发布时间】:2016-07-05 08:50:18
【问题描述】:

我有一个名为:web_data 的 postgres 数据库表

目前我正在运行以下 SQL 选择语句:

SELECT url_path FROM web_data WHERE url_path IS NOT NULL

以下是我将为 url_path 获得的一些示例结果:

/
/aboutus.html
/services.php
/images/twitter_counter.png
/images/facebook_counter.png
/mobile/windows/TileTemplate.xml
/en_US/fbevents.js
/css/style.css

我想返回 url_path 的最终值为以下任一值的结果:

/
.html
.htm
.php
.asp
.aspx
.pdf

有没有办法将它放入 SQL 语句中,而不是获取所有结果,然后使用 PHP 之类的东西进行处理?

【问题讨论】:

    标签: postgresql select where-clause


    【解决方案1】:

    使用LIKE 运算符:

    select url_path
    from web_data
    where url_path like '%.htm'
       or url_path like '%.html'
       or url_path like '%.php'
       or url_path like '%.asp'
       or url_path like '%.aspx'
       or url_path like '%.pdf'
       or url_path like '%/';
    

    http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE

    【讨论】:

    • 所以只有在开头的 % 意味着它必须这样结束?因为使用 LIKE 语法我通常会放 LIKE %.html% 另外,如果我有很多记录,LIKE 函数会很慢吗?
    • @Ahmed: % 是一个通配符 %.html 表示任何以.html结束的值。是的,这会很慢,因为数据库不能为此使用正则索引。如果您确实有那么多行,则需要创建一个 trigram 索引,以便索引会有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    相关资源
    最近更新 更多