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

在本地 SQLite 3.53.1 验证 FULL OUTER JOIN、COALESCE 键合并与 MySQL UNION ALL 等价替代

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。explore-join-full.py
explore-join-full.py235 行
"""Offline SQLite lab for SQL Chapter 22: FULL OUTER JOIN."""
import json
import sqlite3
import sys


def make_case(name: str, summary: str, expected, actual) -> dict:
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    conn = sqlite3.connect(":memory:")
    cur = conn.cursor()

    cur.executescript(
        """
        CREATE TABLE Students (
            StudentID INT,
            Name TEXT
        );
        INSERT INTO Students VALUES
            (1, 'Alice'),
            (2, 'Bob'),
            (3, 'Charlie');

        CREATE TABLE Courses (
            CourseID INT,
            StudentID INT,
            CourseName TEXT
        );
        INSERT INTO Courses VALUES
            (101, 1, 'Math'),
            (102, 2, 'Science'),
            (103, 4, 'History');
        """
    )

    direct_full = [
        list(r)
        for r in cur.execute(
            """
            SELECT Students.StudentID, Students.Name, Courses.CourseName
            FROM Students
            FULL OUTER JOIN Courses
            ON Students.StudentID = Courses.StudentID
            ORDER BY COALESCE(Students.StudentID, Courses.StudentID)
            """
        ).fetchall()
    ]
    coalesced_full = [
        list(r)
        for r in cur.execute(
            """
            SELECT COALESCE(Students.StudentID, Courses.StudentID) AS StudentID,
                   Students.Name,
                   Courses.CourseName
            FROM Students
            FULL OUTER JOIN Courses
            ON Students.StudentID = Courses.StudentID
            ORDER BY StudentID
            """
        ).fetchall()
    ]
    case1 = make_case(
        "students_courses_full_outer_join",
        "Verify FULL OUTER JOIN returns union of Students and Courses, showing direct left-key NULL vs COALESCE",
        {
            "direct": [
                [1, "Alice", "Math"],
                [2, "Bob", "Science"],
                [3, "Charlie", None],
                [None, None, "History"],
            ],
            "coalesced": [
                [1, "Alice", "Math"],
                [2, "Bob", "Science"],
                [3, "Charlie", None],
                [4, None, "History"],
            ],
        },
        {
            "direct": direct_full,
            "coalesced": coalesced_full,
        },
    )

    counts = {
        "inner": cur.execute(
            "SELECT COUNT(*) FROM Students INNER JOIN Courses ON Students.StudentID = Courses.StudentID"
        ).fetchone()[0],
        "left": cur.execute(
            "SELECT COUNT(*) FROM Students LEFT JOIN Courses ON Students.StudentID = Courses.StudentID"
        ).fetchone()[0],
        "right": cur.execute(
            "SELECT COUNT(*) FROM Students RIGHT JOIN Courses ON Students.StudentID = Courses.StudentID"
        ).fetchone()[0],
        "full": cur.execute(
            "SELECT COUNT(*) FROM Students FULL OUTER JOIN Courses ON Students.StudentID = Courses.StudentID"
        ).fetchone()[0],
    }
    case2 = make_case(
        "join_family_comparison",
        "Compare row counts across INNER, LEFT, RIGHT, and FULL OUTER JOIN on Students and Courses",
        {"inner": 2, "left": 3, "right": 3, "full": 4},
        counts,
    )

    cur.executescript(
        """
        CREATE TABLE Websites (
            id INT,
            name TEXT,
            url TEXT,
            alexa INT,
            country TEXT
        );
        INSERT INTO Websites VALUES
            (1, 'Google', 'https://www.google.com/', 1, 'USA'),
            (2, '淘宝', 'https://www.taobao.com/', 13, 'CN'),
            (3, '蓝色天空', 'https://www.mbsky.com/', 4689, 'CN'),
            (4, '微博', 'https://weibo.com/', 20, 'CN'),
            (5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'),
            (7, 'stackoverflow', 'https://stackoverflow.com/', 0, 'IND');

        CREATE TABLE access_log (
            aid INT,
            site_id INT,
            count INT,
            date TEXT
        );
        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');
        """
    )

    site_full = [
        list(r)
        for r in cur.execute(
            """
            SELECT Websites.name, access_log.count, access_log.date
            FROM Websites
            FULL OUTER JOIN access_log
            ON Websites.id = access_log.site_id
            ORDER BY access_log.count DESC, Websites.id ASC
            """
        ).fetchall()
    ]
    case3 = make_case(
        "websites_access_log_full_join",
        "Verify Websites FULL OUTER JOIN access_log returns 10 rows including unmatched stackoverflow",
        {
            "row_count": 10,
            "first_row": ["Facebook", 545, "2016-05-16"],
            "last_row": ["stackoverflow", None, None],
        },
        {
            "row_count": len(site_full),
            "first_row": site_full[0],
            "last_row": site_full[-1],
        },
    )

    # Also test MySQL emulation pattern (LEFT JOIN UNION ALL unmatched RIGHT JOIN) with unmatched rows on both sides
    cur.execute("INSERT INTO access_log VALUES (10, 6, 111, '2016-03-09')")
    native_both = [
        list(r)
        for r in cur.execute(
            """
            SELECT Websites.name, access_log.count, access_log.date
            FROM Websites
            FULL OUTER JOIN access_log ON Websites.id = access_log.site_id
            ORDER BY access_log.count DESC, Websites.name ASC
            """
        ).fetchall()
    ]
    emulated_both = [
        list(r)
        for r in cur.execute(
            """
            SELECT name, count, date FROM (
                SELECT Websites.name AS name, access_log.count AS count, access_log.date AS date
                FROM Websites
                LEFT JOIN access_log ON Websites.id = access_log.site_id
                UNION ALL
                SELECT Websites.name AS name, access_log.count AS count, access_log.date AS date
                FROM Websites
                RIGHT JOIN access_log ON Websites.id = access_log.site_id
                WHERE Websites.id IS NULL
            )
            ORDER BY count DESC, name ASC
            """
        ).fetchall()
    ]
    case4 = make_case(
        "mysql_union_emulation_equivalence",
        "Verify LEFT JOIN + UNION ALL unmatched RIGHT JOIN matches native FULL OUTER JOIN with unmatched rows on both sides",
        {
            "row_count": 11,
            "matches_native": True,
            "has_null_name": True,
            "has_null_count": True,
        },
        {
            "row_count": len(native_both),
            "matches_native": native_both == emulated_both,
            "has_null_name": any(r[0] is None and r[1] == 111 for r in native_both),
            "has_null_count": any(r[0] == "stackoverflow" and r[1] is None for r in native_both),
        },
    )

    conn.close()
    payload = {
        "version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
        "cases": [case1, case2, case3, case4],
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-join-full.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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