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

在本地 SQLite 3.53.1 对比七种 JOIN 类型与站点访问日志内连接

PYTHONWindows x64、CPython 3.12.14、内置 sqlite3(SQLite 3.53.1)本地离线环境。explore-join.py
explore-join.py255 行
"""Offline SQLite lab for SQL Chapter 18: JOIN overview."""
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()

    # 1. Customers & Orders comparison across all JOIN types
    cur.executescript(
        """
        CREATE TABLE Customers (
            CustomerID INT,
            Name TEXT
        );
        INSERT INTO Customers VALUES
            (1, 'Alice'),
            (2, 'Bob'),
            (3, 'Charlie');

        CREATE TABLE Orders (
            OrderID INT,
            CustomerID INT,
            Product TEXT
        );
        INSERT INTO Orders VALUES
            (101, 1, 'Laptop'),
            (102, 2, 'Phone'),
            (103, 4, 'Tablet');
        """
    )

    inner_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT c.CustomerID, c.Name, o.Product
            FROM Customers c
            INNER JOIN Orders o ON c.CustomerID = o.CustomerID
            ORDER BY c.CustomerID
            """
        ).fetchall()
    ]
    left_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT c.CustomerID, c.Name, o.Product
            FROM Customers c
            LEFT JOIN Orders o ON c.CustomerID = o.CustomerID
            ORDER BY c.CustomerID
            """
        ).fetchall()
    ]
    right_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT o.OrderID, c.Name, o.Product
            FROM Customers c
            RIGHT JOIN Orders o ON c.CustomerID = o.CustomerID
            ORDER BY o.OrderID
            """
        ).fetchall()
    ]
    full_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT c.CustomerID, c.Name, o.OrderID, o.Product
            FROM Customers c
            FULL OUTER JOIN Orders o ON c.CustomerID = o.CustomerID
            ORDER BY COALESCE(c.CustomerID, o.CustomerID)
            """
        ).fetchall()
    ]
    cross_count = cur.execute(
        "SELECT COUNT(*) FROM Customers CROSS JOIN Orders"
    ).fetchone()[0]
    natural_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT CustomerID, Name, OrderID, Product
            FROM Customers NATURAL JOIN Orders
            ORDER BY CustomerID
            """
        ).fetchall()
    ]

    case1 = make_case(
        "customers_orders_all_joins",
        "Verify INNER, LEFT, RIGHT, FULL OUTER, CROSS, and NATURAL JOIN on Customers and Orders",
        {
            "inner": [[1, "Alice", "Laptop"], [2, "Bob", "Phone"]],
            "left": [[1, "Alice", "Laptop"], [2, "Bob", "Phone"], [3, "Charlie", None]],
            "right": [[101, "Alice", "Laptop"], [102, "Bob", "Phone"], [103, None, "Tablet"]],
            "full": [
                [1, "Alice", 101, "Laptop"],
                [2, "Bob", 102, "Phone"],
                [3, "Charlie", None, None],
                [None, None, 103, "Tablet"],
            ],
            "cross_count": 9,
            "natural": [[1, "Alice", 101, "Laptop"], [2, "Bob", 102, "Phone"]],
        },
        {
            "inner": inner_rows,
            "left": left_rows,
            "right": right_rows,
            "full": full_rows,
            "cross_count": cross_count,
            "natural": natural_rows,
        },
    )

    # 2. SELF JOIN hierarchy
    cur.executescript(
        """
        CREATE TABLE Staff (
            StaffID INT,
            Name TEXT,
            ManagerID INT
        );
        INSERT INTO Staff VALUES
            (1, 'Director', NULL),
            (2, 'Alice', 1),
            (3, 'Bob', 2);
        """
    )
    self_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT e.Name AS employee, m.Name AS manager
            FROM Staff e
            LEFT JOIN Staff m ON e.ManagerID = m.StaffID
            ORDER BY e.StaffID
            """
        ).fetchall()
    ]
    case2 = make_case(
        "self_join_hierarchy",
        "Verify SELF JOIN pairing employees with their managers in the same table",
        [["Director", None], ["Alice", "Director"], ["Bob", "Alice"]],
        self_rows,
    )

    # 3. Websites & access_log INNER JOIN
    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_join_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT Websites.id, Websites.name, access_log.count, access_log.date
            FROM Websites
            INNER JOIN access_log ON Websites.id = access_log.site_id
            ORDER BY access_log.aid
            """
        ).fetchall()
    ]
    case3 = make_case(
        "websites_access_log_inner_join",
        "Verify INNER JOIN between Websites and access_log returns 9 matched rows and omits id=7",
        {
            "row_count": 9,
            "first_row": [1, "Google", 45, "2016-05-10"],
            "last_row": [3, "蓝色天空", 201, "2016-05-17"],
            "distinct_ids": [1, 2, 3, 4, 5],
        },
        {
            "row_count": len(site_join_rows),
            "first_row": site_join_rows[0],
            "last_row": site_join_rows[-1],
            "distinct_ids": sorted({r[0] for r in site_join_rows}),
        },
    )

    # 4. JOIN vs INNER JOIN equivalence
    plain_join_rows = [
        list(r)
        for r in cur.execute(
            """
            SELECT Websites.id, Websites.name, access_log.count, access_log.date
            FROM Websites
            JOIN access_log ON Websites.id = access_log.site_id
            ORDER BY access_log.aid
            """
        ).fetchall()
    ]
    case4 = make_case(
        "join_syntax_equivalence",
        "Verify plain JOIN produces the exact same result set as INNER JOIN",
        True,
        plain_join_rows == site_join_rows,
    )

    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-lab/explore-join.py

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

下载课程关联工程包:SQL

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

下载课程关联工程包:SQL

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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