各类资料学习下载合集

​https://pan.quark.cn/s/8c91ccb5a474​

数据库自然连接详解

自然连接(Natural Join)是一种在关系型数据库中用于合并两个或多个表的数据的操作。它基于表之间的公共列,自动识别具有相同列名的列,并将匹配的行合并在一起。自然连接可以简化查询操作,避免手动指定连接条件。在本文中,我们将深入探讨自然连接的概念、用法,并通过Python和SQLite进行示例演示。

1. 自然连接的基本概念

1.1 定义

自然连接是一种特殊类型的连接,它根据表之间的同名列进行连接。在自然连接中,只有一列结果将显示在结果集中,而不是显示重复的列。

1.2 语法

自然连接的基本语法如下:

SELECT *
FROM table1
NATURAL JOIN table2;

1.3 特点

  • 自动识别:自然连接会自动识别两个表中相同名称的列。
  • 消除重复列:在结果集中,相同列只会出现一次。

2. 使用SQLite进行自然连接

我们将通过Python的​​sqlite3​​模块创建一个数据库,展示如何使用自然连接。

2.1 创建数据库和表

首先,我们创建一个SQLite数据库和两个表:​​students​​ 和 ​​courses​​,并插入一些示例数据。

import sqlite3

def create_database():
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    
    # 创建学生表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS students (
            student_id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            course_id INTEGER NOT NULL
        )
    ''')
    
    # 创建课程表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS courses (
            course_id INTEGER PRIMARY KEY,
            course_name TEXT NOT NULL
        )
    ''')
    
    connection.commit()
    cursor.close()
    connection.close()

if __name__ == "__main__":
    create_database()

2.2 插入数据

接下来,我们向这两个表中插入一些数据。

def insert_student(student_id, name, course_id):
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('INSERT INTO students (student_id, name, course_id) VALUES (?, ?, ?)', (student_id, name, course_id))
    connection.commit()
    cursor.close()
    connection.close()

def insert_course(course_id, course_name):
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('INSERT INTO courses (course_id, course_name) VALUES (?, ?)', (course_id, course_name))
    connection.commit()
    cursor.close()
    connection.close()

if __name__ == "__main__":
    # 插入学生数据
    students_data = [
        (1, 'Alice', 101),
        (2, 'Bob', 102),
        (3, 'Charlie', 101),
        (4, 'David', 103)
    ]
    
    for student in students_data:
        insert_student(*student)
    
    # 插入课程数据
    courses_data = [
        (101, 'Mathematics'),
        (102, 'Physics'),
        (103, 'Chemistry')
    ]
    
    for course in courses_data:
        insert_course(*course)

2.3 自然连接查询

现在我们将展示如何使用自然连接来查询学生及其所选课程的信息。

def fetch_students_with_courses():
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('''
        SELECT *
        FROM students
        NATURAL JOIN courses
    ''')
    rows = cursor.fetchall()
    cursor.close()
    connection.close()
    return rows

if __name__ == "__main__":
    print("学生及其课程信息:", fetch_students_with_courses())

3. 代码整合

下面是将上面所有代码整合到一个完整的程序中。

import sqlite3

def create_database():
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    
    # 创建学生表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS students (
            student_id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            course_id INTEGER NOT NULL
        )
    ''')
    
    # 创建课程表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS courses (
            course_id INTEGER PRIMARY KEY,
            course_name TEXT NOT NULL
        )
    ''')
    
    connection.commit()
    cursor.close()
    connection.close()

def insert_student(student_id, name, course_id):
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('INSERT INTO students (student_id, name, course_id) VALUES (?, ?, ?)', (student_id, name, course_id))
    connection.commit()
    cursor.close()
    connection.close()

def insert_course(course_id, course_name):
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('INSERT INTO courses (course_id, course_name) VALUES (?, ?)', (course_id, course_name))
    connection.commit()
    cursor.close()
    connection.close()

def fetch_students_with_courses():
    connection = sqlite3.connect('school.db')
    cursor = connection.cursor()
    cursor.execute('''
        SELECT *
        FROM students
        NATURAL JOIN courses
    ''')
    rows = cursor.fetchall()
    cursor.close()
    connection.close()
    return rows

if __name__ == "__main__":
    # 创建数据库和表
    create_database()
    
    # 插入数据
    students_data = [
        (1, 'Alice', 101),
        (2, 'Bob', 102),
        (3, 'Charlie', 101),
        (4, 'David', 103)
    ]
    
    for student in students_data:
        insert_student(*student)
    
    courses_data = [
        (101, 'Mathematics'),
        (102, 'Physics'),
        (103, 'Chemistry')
    ]
    
    for course in courses_data:
        insert_course(*course)

    # 查询学生及其课程信息
    print("学生及其课程信息:", fetch_students_with_courses())

4. 运行结果

运行此完整的程序将产生类似以下的输出:

学生及其课程信息: [(1, 'Alice', 101, 'Mathematics'), (3, 'Charlie', 101, 'Mathematics'), (2, 'Bob', 102, 'Physics'), (4, 'David', 103, 'Chemistry')]

在输出结果中,每一行代表一个学生及其对应的课程信息,其中包含学生的 ​​student_id​​、​​name​​ 和选修课程的 ​​course_id​​ 和 ​​course_name​​。

Logo

一站式 AI 云服务平台

更多推荐