蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 SQLite 3.53 列别名、含空格标识、CONCAT/|| 多列组合与多表表别名等价实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-alias.py
explore-alias.py178 行
"""SQL 别名离线实验:验证列别名、含空格标识引号、多列拼接别名与多表联查表别名等价性。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    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');

        CREATE TABLE access_log (
            aid INTEGER PRIMARY KEY,
            site_id INTEGER NOT NULL,
            count INTEGER NOT NULL,
            date TEXT NOT NULL
        );
        INSERT INTO access_log VALUES
            (1, 1, 45, '2016-05-10'),
            (2, 3, 100, '2016-05-13'),
            (3, 1, 230, '2016-05-14'),
            (4, 2, 10, '2016-05-14'),
            (5, 5, 205, '2016-05-14'),
            (6, 4, 13, '2016-05-15'),
            (7, 3, 220, '2016-05-15'),
            (8, 5, 545, '2016-05-16'),
            (9, 3, 201, '2016-05-17');
        """
    )
    cases = []

    # Case 1: Column aliases & aliases containing spaces (double quotes / brackets)
    cur1 = conn.execute("SELECT name AS n, country AS c FROM websites ORDER BY id;")
    cols1 = [d[0] for d in cur1.description]
    rows1 = [list(r) for r in cur1.fetchall()]
    cur_sp = conn.execute(
        'SELECT name AS "Site Name", country AS [Country Code] FROM websites ORDER BY id LIMIT 2;'
    )
    cols_sp = [d[0] for d in cur_sp.description]
    exp1 = {
        "short_alias_columns": ["n", "c"],
        "first_two_rows": [["Google", "USA"], ["淘宝", "CN"]],
        "spaced_alias_columns": ["Site Name", "Country Code"],
    }
    act1 = {
        "short_alias_columns": cols1,
        "first_two_rows": rows1[:2],
        "spaced_alias_columns": cols_sp,
    }
    cases.append(
        {
            "name": "column_alias_and_spaced_identifier",
            "summary": "验证 name AS n、country AS c 输出列名及含空格别名的双引号/方括号写法",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: Combining three columns into site_info via CONCAT() and ANSI ||
    cur_concat = conn.execute(
        "SELECT name, CONCAT(url, ', ', alexa, ', ', country) AS site_info FROM websites ORDER BY id;"
    )
    concat_cols = [d[0] for d in cur_concat.description]
    concat_rows = [list(r) for r in cur_concat.fetchall()]
    pipe_rows = [
        list(r)
        for r in conn.execute(
            "SELECT name, (url || ', ' || alexa || ', ' || country) AS site_info FROM websites ORDER BY id;"
        ).fetchall()
    ]
    exp2 = {
        "columns": ["name", "site_info"],
        "sample_rows": [
            ["Google", "https://www.google.com/, 1, USA"],
            ["蓝色天空", "http://www.mbsky.com/, 5000, USA"],
        ],
        "concat_matches_pipe_operator": True,
    }
    act2 = {
        "columns": concat_cols,
        "sample_rows": [concat_rows[0], concat_rows[2]],
        "concat_matches_pipe_operator": concat_rows == pipe_rows,
    }
    cases.append(
        {
            "name": "column_alias_concat_expression",
            "summary": "将 url、alexa、country 组合为别名 site_info,验证 SQLite 3.53 CONCAT() 与 ANSI || 结果一致",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: Table aliases w & a vs full table names + aggregate alias
    aliased = [
        list(r)
        for r in conn.execute(
            """
            SELECT w.name, w.url, a.count, a.date
            FROM websites AS w, access_log AS a
            WHERE a.site_id = w.id AND w.name = '蓝色天空'
            ORDER BY a.aid;
            """
        ).fetchall()
    ]
    unaliased = [
        list(r)
        for r in conn.execute(
            """
            SELECT websites.name, websites.url, access_log.count, access_log.date
            FROM websites, access_log
            WHERE websites.id = access_log.site_id AND websites.name = '蓝色天空'
            ORDER BY access_log.aid;
            """
        ).fetchall()
    ]
    agg_cur = conn.execute(
        """
        SELECT w.name AS site_name, SUM(a.count) AS total_views
        FROM websites AS w
        INNER JOIN access_log AS a ON w.id = a.site_id
        WHERE w.name = '蓝色天空'
        GROUP BY w.id, w.name;
        """
    )
    agg_cols = [d[0] for d in agg_cur.description]
    agg_row = list(agg_cur.fetchone())
    exp3 = {
        "aliased_rows": [
            ["蓝色天空", "http://www.mbsky.com/", 100, "2016-05-13"],
            ["蓝色天空", "http://www.mbsky.com/", 220, "2016-05-15"],
            ["蓝色天空", "http://www.mbsky.com/", 201, "2016-05-17"],
        ],
        "matches_unaliased_query": True,
        "aggregate_columns": ["site_name", "total_views"],
        "aggregate_row": ["蓝色天空", 521],
    }
    act3 = {
        "aliased_rows": aliased,
        "matches_unaliased_query": aliased == unaliased,
        "aggregate_columns": agg_cols,
        "aggregate_row": agg_row,
    }
    cases.append(
        {
            "name": "table_alias_multi_table_join",
            "summary": "对比表别名 w/a 与完整表名联查访问日志,验证结果完全一致并核对聚合函数列别名",
            "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))
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/sql-alias-lab/explore-alias.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-alias.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

课程关联工程包(登记关联67章) · 含当前章节或实例 · mbskycom202612a1523.zip

下载课程关联工程包:SQL

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1520.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习