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

在本地 SQLite 3.53.1 验证 RIGHT JOIN、与 LEFT JOIN 对称等价性及访问日志右连接

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。explore-join-right.py
explore-join-right.py198 行
"""Offline SQLite lab for SQL Chapter 21: RIGHT 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 Employees (
            EmployeeID INT,
            Name TEXT,
            DepartmentID INT
        );
        INSERT INTO Employees VALUES
            (1, 'Alice', 10),
            (2, 'Bob', 20),
            (3, 'Charlie', NULL);

        CREATE TABLE Departments (
            DepartmentID INT,
            DepartmentName TEXT
        );
        INSERT INTO Departments VALUES
            (10, 'HR'),
            (20, 'IT'),
            (30, 'Finance');
        """
    )

    right_res = [
        list(r)
        for r in cur.execute(
            """
            SELECT Employees.Name, Departments.DepartmentName
            FROM Employees
            RIGHT JOIN Departments
            ON Employees.DepartmentID = Departments.DepartmentID
            ORDER BY Departments.DepartmentID
            """
        ).fetchall()
    ]
    right_outer_res = [
        list(r)
        for r in cur.execute(
            """
            SELECT Employees.Name, Departments.DepartmentName
            FROM Employees
            RIGHT OUTER JOIN Departments
            ON Employees.DepartmentID = Departments.DepartmentID
            ORDER BY Departments.DepartmentID
            """
        ).fetchall()
    ]

    case1 = make_case(
        "right_join_vs_right_outer_join",
        "Verify RIGHT JOIN and RIGHT OUTER JOIN preserve all Departments including Finance with NULL Name",
        {
            "rows": [["Alice", "HR"], ["Bob", "IT"], [None, "Finance"]],
            "same_as_right_outer": True,
        },
        {
            "rows": right_res,
            "same_as_right_outer": right_res == right_outer_res,
        },
    )

    swapped_left = [
        list(r)
        for r in cur.execute(
            """
            SELECT Employees.Name, Departments.DepartmentName
            FROM Departments
            LEFT JOIN Employees
            ON Employees.DepartmentID = Departments.DepartmentID
            ORDER BY Departments.DepartmentID
            """
        ).fetchall()
    ]
    emp_left = [
        list(r)
        for r in cur.execute(
            """
            SELECT Employees.Name, Departments.DepartmentName
            FROM Employees
            LEFT JOIN Departments
            ON Employees.DepartmentID = Departments.DepartmentID
            ORDER BY Employees.EmployeeID
            """
        ).fetchall()
    ]
    case2 = make_case(
        "right_join_vs_left_join_symmetry",
        "Verify Departments LEFT JOIN Employees equals Employees RIGHT JOIN Departments, contrasting with Employees LEFT JOIN Departments",
        {
            "swapped_left_equals_right": True,
            "employees_left_rows": [["Alice", "HR"], ["Bob", "IT"], ["Charlie", None]],
        },
        {
            "swapped_left_equals_right": swapped_left == right_res,
            "employees_left_rows": emp_left,
        },
    )

    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');

        INSERT INTO access_log (aid, site_id, count, date)
        VALUES (10, 6, 111, '2016-03-09');
        """
    )

    site_right = [
        list(r)
        for r in cur.execute(
            """
            SELECT Websites.name, access_log.count, access_log.date
            FROM Websites
            RIGHT JOIN access_log
            ON access_log.site_id = Websites.id
            ORDER BY access_log.count DESC
            """
        ).fetchall()
    ]
    unmatched_log_rows = [r for r in site_right if r[0] is None]
    case3 = make_case(
        "websites_right_join_access_log",
        "Verify Websites RIGHT JOIN access_log keeps unmatched site_id=6 row with NULL name and excludes stackoverflow",
        {
            "row_count": 10,
            "top_row": ["Facebook", 545, "2016-05-16"],
            "unmatched_rows": [[None, 111, "2016-03-09"]],
            "has_stackoverflow": False,
        },
        {
            "row_count": len(site_right),
            "top_row": site_right[0],
            "unmatched_rows": unmatched_log_rows,
            "has_stackoverflow": any(r[0] == "stackoverflow" for r in site_right),
        },
    )

    conn.close()
    payload = {
        "version": f"CPython {sys.version.split()[0]} / SQLite {sqlite3.sqlite_version}",
        "cases": [case1, case2, case3],
    }
    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-right-lab/explore-join-right.py

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

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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