蓝色天空网mbsky.com · 知识 · 实践 · 创造SQL · 本地阅读预览
教程 / 数据库 / SQL

SQL 通配符

系统核对 SQL 模式匹配中的 %、_、[charlist] 与 [^charlist]/[!charlist] 通配符语义及跨数据库差异(SQL Server LIKE、MS Access、MySQL REGEXP、SQLite GLOB/自定义 REGEXP),并在本地 SQLite 中实测全部模式。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

SQL 通配符类型与跨数据库语法差异

SQL 通配符用于在字符串模式匹配中替代一个或多个未知字符,通常与 `LIKE` 操作符配合检索数据。标准 SQL 定义了 `%`(替代 0 个或多个字符)与 `_`(替代单个字符);在此基础上,SQL Server 的 `LIKE` 额外支持字符类 `[charlist]` 与取反 `[^charlist]`,MS Access 使用 `*`、`?` 与 `[!charlist]`,而 MySQL 与 PostgreSQL 的标准 `LIKE` 并不解析方括号字符类,需要改用正则表达式运算符(如 MySQL 的 `REGEXP`/`RLIKE` 或 PostgreSQL 的 `~`);SQLite 则原生提供区分大小写的 Unix 风格 `GLOB`(支持 `*`、`?`、`[charlist]`、`[^charlist]`)并允许注册自定义 `REGEXP` 函数。

% 与 _ 通配符实测

在 6 行 `websites` 演示表上使用 `%` 通配符:`WHERE url LIKE 'https%'` 选取以 `https` 开头的安全链接站点,本站 SQLite 3.53.1 实测命中 `['Google', '淘宝', 'Facebook']`(自动排除 3 条 `http://` 记录);`WHERE url LIKE '%oo%'` 选取网址包含 `oo` 的站点,实测命中 `['Google', 'Facebook']`。

使用单字符通配符 `_` 可精确锁定字符长度与位置:`WHERE name LIKE '_oogle'` 匹配任意首字符后紧跟 `oogle` 的 6 字符名称,`WHERE name LIKE 'G_o_le'` 匹配第 1、3、5–6 位固定且第 2、4 位为任意单字符的名称。本站实测两条语句均精准命中 `['Google']`。

[charlist] 字符类与 REGEXP / GLOB 实测

`[charlist]` 用于匹配字符列表或区间内的任意单个字符,在 MySQL 中通常写作 `REGEXP` 正则表达式:`WHERE name REGEXP '^[GFs]'` 匹配以 `G`、`F` 或 `s` 开头的站点,`WHERE name REGEXP '^[A-H]'` 匹配以 `A` 到 `H` 大写字母开头的站点,`WHERE name REGEXP '^[^A-H]'` 匹配不以 `A` 到 `H` 开头的站点。本站实验在 SQLite 3.53.1 中通过 `conn.create_function('REGEXP', 2, ...)` 注册 Python `re.search`,并同时与 SQLite 原生 `GLOB`(`'[GFs]*'`、`'[A-H]*'`、`'[^A-H]*'`)交叉验证,二者返回完全一致的结果:`^[GFs]` 命中 `['Google', 'Facebook', 'stackoverflow']`,`^[A-H]` 命中 `['Google', 'Facebook']`,`^[^A-H]` 命中 `['淘宝', '蓝色天空', '微博', 'stackoverflow']`。

SQL 常用通配符与字符类参考表

通配符匹配说明
%替代 0 个、1 个或多个任意字符(MS Access 中对应 *),实测 url LIKE 'https%' 命中 3 条。
_严格替代单个任意字符(MS Access 中对应 ?),实测 name LIKE 'G_o_le' 精准命中 Google。
[charlist]匹配方括号字符列表或区间中的任一单字符(SQL Server LIKE、SQLite GLOB 及 MySQL REGEXP 支持),实测 ^[GFs] 命中 3 条。
[^charlist] 或 [!charlist]匹配不在指定字符列表或区间内的任一单字符(SQL Server/REGEXP/GLOB 用 ^,MS Access 用 !),实测 ^[^A-H] 命中 4 条。

运行 SQLite 3.53 %/_ 通配符、自定义 REGEXP 与原生 GLOB 字符类交叉实测

python · 阅读源码
"""SQL 通配符离线实验:验证 %、_ 与字符集模式(SQLite 自定义 REGEXP 函数及原生 GLOB)。"""
import json
import platform
import re
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.create_function(
        "REGEXP",
        2,
        lambda pattern, value: bool(re.search(pattern, value)) if value is not None else False,
    )
    conn.executescript(
        """
        CREATE TABLE websites (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            url TEXT NOT NULL,
            alexa INTEGER NOT NULL,
            country TEXT NOT NULL
        );
        INSERT INTO websites VALUES
            (1, 'Google', 'https://www.google.com/', 1, 'USA'),
            (2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
            (3, '蓝色天空', 'http://www.mbsky.com/', 5000, 'USA'),
            (4, '微博', 'http://weibo.com/', 20, 'CN'),
            (5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
            (7, 'stackoverflow', 'http://stackoverflow.com/', 0, 'IND');
        """
    )
    cases = []

    # Case 1: % wildcard on url
    https_sites = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE url LIKE 'https%' ORDER BY id;"
        ).fetchall()
    ]
    oo_urls = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE url LIKE '%oo%' ORDER BY id;"
        ).fetchall()
    ]
    exp1 = {
        "url_https": ["Google", "淘宝", "Facebook"],
        "url_contains_oo": ["Google", "Facebook"],
    }
    act1 = {"url_https": https_sites, "url_contains_oo": oo_urls}
    cases.append(
        {
            "name": "wildcard_percent_url_patterns",
            "summary": "使用 % 通配符筛选 url 以 https 开头及包含 oo 的网站记录",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: _ single-character wildcard on name
    under1 = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name LIKE '_oogle' ORDER BY id;"
        ).fetchall()
    ]
    under2 = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name LIKE 'G_o_le' ORDER BY id;"
        ).fetchall()
    ]
    exp2 = {"pattern_oogle": ["Google"], "pattern_G_o_le": ["Google"]}
    act2 = {"pattern_oogle": under1, "pattern_G_o_le": under2}
    cases.append(
        {
            "name": "wildcard_underscore_single_char",
            "summary": "使用 _ 单字符通配符验证 '_oogle' 与 'G_o_le' 精准定位 Google",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: Character classes via REGEXP UDF and native SQLite GLOB
    re_gfs = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name REGEXP '^[GFs]' ORDER BY id;"
        ).fetchall()
    ]
    re_ah = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name REGEXP '^[A-H]' ORDER BY id;"
        ).fetchall()
    ]
    re_not_ah = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name REGEXP '^[^A-H]' ORDER BY id;"
        ).fetchall()
    ]
    glob_gfs = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name GLOB '[GFs]*' ORDER BY id;"
        ).fetchall()
    ]
    glob_ah = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name GLOB '[A-H]*' ORDER BY id;"
        ).fetchall()
    ]
    glob_not_ah = [
        r[0]
        for r in conn.execute(
            "SELECT name FROM websites WHERE name GLOB '[^A-H]*' ORDER BY id;"
        ).fetchall()
    ]
    exp3 = {
        "regexp_GFs": ["Google", "Facebook", "stackoverflow"],
        "regexp_A_H": ["Google", "Facebook"],
        "regexp_not_A_H": ["淘宝", "蓝色天空", "微博", "stackoverflow"],
        "glob_matches_regexp": True,
    }
    act3 = {
        "regexp_GFs": re_gfs,
        "regexp_A_H": re_ah,
        "regexp_not_A_H": re_not_ah,
        "glob_matches_regexp": (re_gfs == glob_gfs and re_ah == glob_ah and re_not_ah == glob_not_ah),
    }
    cases.append(
        {
            "name": "wildcard_charlist_regexp_and_glob",
            "summary": "通过 SQLite 注册 REGEXP 与原生 GLOB 验证 ^[GFs]、^[A-H] 与 ^[^A-H] 字符集合匹配",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version}",
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(run(), ensure_ascii=False, indent=2))
预期结果 · 待实际运行核验
  • 验证 url 的 https% 与 %oo%、name 的 _oogle 与 G_o_le,以及 ^[GFs]、^[A-H]、^[^A-H] 在 REGEXP 与 GLOB 下完全一致的命中集合。
运行 SQLite 3.53 %/_ 通配符、自定义 REGEXP 与原生 GLOB 字符类交叉实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:c18484ac9db7e4ac52da0621914dc7301a91950a4fa41a4b2ff416515e640e56

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载SQL 通配符实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:e6f16909715cd63bc826406dd6fb20bbdaa10b28d4c4eb6730eafeced75c2180

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 MySQL 或 SQLite 中直接执行 `WHERE name LIKE '[A-H]%'` 无法按预期匹配 A 到 H 开头的站点?应改用什么写法?

展开参考解答

因为 MySQL 与 SQLite 的 `LIKE` 把 `[` 和 `]` 当作普通字面字符而不解析字符类;MySQL 应改用 `WHERE name REGEXP '^[A-H]'`,SQLite 可改用原生 `WHERE name GLOB '[A-H]*'` 或注册 `REGEXP` 函数。

规范与官方依据