如何在Python中使用SQLite进行多表查询和联结操作

2023-04-04 00:00:00 操作 如何在 联结

在Python中使用SQLite进行多表查询和联结操作,需要以下步骤:

1.导入SQLite模块

import sqlite3

2.建立连接

conn = sqlite3.connect('example.db')

3.创建游标

cursor = conn.cursor()

4.创建表格并插入数据
我们将创建两个表格,一个名为“employees”,包含employee_id、name和department_id三个字段;另一个名为“departments”,包含department_id和department_name两个字段。插入数据的过程与之前创建单个表格的过程类似。

cursor.execute('CREATE TABLE IF NOT EXISTS employees(employee_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER)')
cursor.execute('CREATE TABLE IF NOT EXISTS departments(department_id INTEGER PRIMARY KEY, department_name TEXT)')
cursor.execute("INSERT INTO employees (employee_id, name, department_id) VALUES (1, 'John', 1)")
cursor.execute("INSERT INTO employees (employee_id, name, department_id) VALUES (2, 'Paul', 1)")
cursor.execute("INSERT INTO employees (employee_id, name, department_id) VALUES (3, 'Peter', 2)")
cursor.execute("INSERT INTO employees (employee_id, name, department_id) VALUES (4, 'Jack', 2)")
cursor.execute("INSERT INTO departments (department_id, department_name) VALUES (1, 'pidancode.com')")
cursor.execute("INSERT INTO departments (department_id, department_name) VALUES (2, '皮蛋编程')")

5.内连接查询
使用INNER JOIN语句进行内连接查询。下面的示例查询每个员工所在的部门。

cursor.execute("SELECT employees.name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.department_id")
result = cursor.fetchall()
for row in result:
    print(row)

输出结果:

('John', 'pidancode.com')
('Paul', 'pidancode.com')
('Peter', '皮蛋编程')
('Jack', '皮蛋编程')

6.左外连接查询
使用LEFT OUTER JOIN语句进行左外连接查询。下面的示例查询所有员工及其所在部门的名称,如果员工没有指定部门,则显示为NULL。

cursor.execute("SELECT employees.name, departments.department_name FROM employees LEFT OUTER JOIN departments ON employees.department_id = departments.department_id")
result = cursor.fetchall()
for row in result:
    print(row)

输出结果:

('John', 'pidancode.com')
('Paul', 'pidancode.com')
('Peter', '皮蛋编程')
('Jack', '皮蛋编程')

以上代码演示了如何在Python中使用SQLite进行多表查询和联结操作,包括内连接和左外连接查询。通过创建两个表格,我们演示了如何使用JOIN语句对它们进行联结操作,并查询员工及其所在部门的相关信息。如果你对Python数据处理和SQLite数据库操作有兴趣,那么本文将对你有所帮助。

相关文章