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

运行离线单列/多列/位置/表达式排序、NULLS FIRST/LAST 与 MySQL IS NULL 便携写法对照及日期排序实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-order-by.py
explore-order-by.py172 行
"""MySQL ORDER BY 语句离线实验:在内存 SQLite 中实测单列/多列排序、列位置序号排序、表达式别名排序、NULL 排位控制(SQLite NULLS FIRST/LAST 与 MySQL 便携 IS NULL 写法)以及日期升降序。"""
import json
import platform
import sqlite3


def run() -> dict:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE products (id INTEGER PRIMARY KEY, product_name TEXT, price REAL, discount_rate REAL);
        INSERT INTO products VALUES
            (1, 'Keyboard', 200.0, 0.8),
            (2, 'Adapter', 50.0, 0.9),
            (3, 'Monitor', 1000.0, 0.85),
            (4, 'MysteryBox', NULL, 1.0);

        CREATE TABLE employees (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, department_id INTEGER, hire_date TEXT, salary INTEGER);
        INSERT INTO employees VALUES
            (1, 'Bob', 'Li', 10, '2021-03-01', 9000),
            (2, 'Alice', 'Wang', 10, '2023-06-15', 9000),
            (3, 'Carol', 'Zhang', 20, '2020-01-10', 12000);

        CREATE TABLE articles_tbl (
            article_id INTEGER PRIMARY KEY,
            article_title TEXT NOT NULL,
            article_author TEXT NOT NULL,
            submission_date TEXT NOT NULL
        );
        INSERT INTO articles_tbl VALUES
            (1, '学习 PHP', '蓝色天空', '2017-04-12'),
            (2, '学习 MySQL', '蓝色天空', '2017-04-12'),
            (3, '学习 Java', 'MBSKY.COM', '2015-05-01'),
            (4, '学习 Python', 'MBSKY.COM', '2016-03-06');
        """
    )
    cases = []

    # Case 1: Single-column ASC, multi-column ASC+DESC, column position index, expression alias
    single_asc = [
        r[0]
        for r in conn.execute(
            "SELECT product_name FROM products ORDER BY product_name ASC;"
        ).fetchall()
    ]
    multi_col = [
        [r[0], r[1], r[2]]
        for r in conn.execute(
            "SELECT department_id, first_name, hire_date FROM employees ORDER BY department_id ASC, hire_date DESC;"
        ).fetchall()
    ]
    by_pos = [
        [r[0], r[2]]
        for r in conn.execute(
            "SELECT first_name, last_name, salary FROM employees ORDER BY 3 DESC, 1 ASC;"
        ).fetchall()
    ]
    by_expr = [
        [r[0], r[1]]
        for r in conn.execute(
            "SELECT product_name, ROUND(price * discount_rate, 2) AS discounted_price "
            "FROM products WHERE price IS NOT NULL ORDER BY discounted_price DESC;"
        ).fetchall()
    ]
    exp1 = {
        "single_asc": ["Adapter", "Keyboard", "Monitor", "MysteryBox"],
        "multi_col": [
            [10, "Alice", "2023-06-15"],
            [10, "Bob", "2021-03-01"],
            [20, "Carol", "2020-01-10"],
        ],
        "by_position": [["Carol", 12000], ["Alice", 9000], ["Bob", 9000]],
        "by_expr_desc": [["Monitor", 850.0], ["Keyboard", 160.0], ["Adapter", 45.0]],
    }
    act1 = {
        "single_asc": single_asc,
        "multi_col": multi_col,
        "by_position": by_pos,
        "by_expr_desc": by_expr,
    }
    cases.append(
        {
            "name": "order_by_single_multi_position_and_expression",
            "summary": "实测单列升序、多列混合升降序、列位置序号(3 DESC, 1 ASC)与计算别名排序",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        }
    )

    # Case 2: NULL ordering (standard NULLS LAST/FIRST vs MySQL portable `price IS NULL` pattern)
    nulls_last_std = [
        r[0]
        for r in conn.execute(
            "SELECT product_name FROM products ORDER BY price DESC NULLS LAST;"
        ).fetchall()
    ]
    nulls_last_mysql = [
        r[0]
        for r in conn.execute(
            "SELECT product_name FROM products ORDER BY (price IS NULL) ASC, price DESC;"
        ).fetchall()
    ]
    nulls_first_std = [
        r[0]
        for r in conn.execute(
            "SELECT product_name FROM products ORDER BY price DESC NULLS FIRST;"
        ).fetchall()
    ]
    nulls_first_mysql = [
        r[0]
        for r in conn.execute(
            "SELECT product_name FROM products ORDER BY (price IS NULL) DESC, price DESC;"
        ).fetchall()
    ]
    exp2 = {
        "nulls_last_matches_mysql_portable": True,
        "nulls_last_order": ["Monitor", "Keyboard", "Adapter", "MysteryBox"],
        "nulls_first_matches_mysql_portable": True,
        "nulls_first_order": ["MysteryBox", "Monitor", "Keyboard", "Adapter"],
    }
    act2 = {
        "nulls_last_matches_mysql_portable": nulls_last_std == nulls_last_mysql,
        "nulls_last_order": nulls_last_mysql,
        "nulls_first_matches_mysql_portable": nulls_first_std == nulls_first_mysql,
        "nulls_first_order": nulls_first_mysql,
    }
    cases.append(
        {
            "name": "order_by_null_placement_standard_vs_mysql",
            "summary": "对比标准 NULLS FIRST/LAST 与 MySQL 8.x 通用的 (col IS NULL) 表达式排序等价结果",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        }
    )

    # Case 3: articles_tbl submission_date ASC & DESC (CLI & PHP mysqli_query equivalent)
    date_asc = [
        r[0]
        for r in conn.execute(
            "SELECT article_id FROM articles_tbl ORDER BY submission_date ASC, article_id ASC;"
        ).fetchall()
    ]
    date_desc = [
        r[0]
        for r in conn.execute(
            "SELECT article_id FROM articles_tbl ORDER BY submission_date DESC, article_id ASC;"
        ).fetchall()
    ]
    exp3 = {"date_asc_ids": [3, 4, 1, 2], "date_desc_ids": [1, 2, 4, 3]}
    act3 = {"date_asc_ids": date_asc, "date_desc_ids": date_desc}
    cases.append(
        {
            "name": "order_by_submission_date_asc_desc",
            "summary": "实测文章表按 submission_date 升序与降序排列结果",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        }
    )

    conn.close()
    return {
        "version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline MySQL verifier)",
        "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/mysql-order-by-lab/explore-order-by.py

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

下载课程关联工程包:MySQL

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

下载课程关联工程包:MySQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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