
- Python SQLite 教程
- Python SQLite - 首頁
- Python SQLite - 簡介
- Python SQLite - 建立連線
- Python SQLite - 建立表
- Python SQLite - 插入資料
- Python SQLite - 選擇資料
- Python SQLite - WHERE 子句
- Python SQLite - ORDER BY
- Python SQLite - 更新表
- Python SQLite - 刪除資料
- Python SQLite - 刪除表
- Python SQLite - LIMIT
- Python SQLite - 聯接
- Python SQLite - 遊標物件
- Python SQLite 實用資源
- Python SQLite - 快速指南
- Python SQLite - 實用資源
- Python SQLite - 討論
Python SQLite - 聯接
將資料分隔成兩個表之後,你可以使用聯接從這兩個表中提取合併記錄。
示例
假設我們使用以下查詢建立了一個名稱為 CRICKETERS 的表 -
sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite>
讓我們建立一個名為 OdiStats 的表,用於描述 CRICKETERS 表中每個球員的單日板球統計資料。
sqlite> CREATE TABLE ODIStats ( First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, Centuries INT, HalfCenturies INT ); sqlite>
以下語句檢索合並這兩個表中的值的資料 -
sqlite> SELECT Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country, OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name; First_Name Last_Name Country Matches Runs Centuries HalfCenturies ---------- ---------- ------- ------- ---- --------- -------------- Shikhar Dhawan Indi 133 5518 17 27 Jonathan Trott Sout 68 2819 4 22 Kumara Sangakkara Sril 404 14234 25 93 Virat Kohli Indi 239 11520 43 54 Rohit Sharma Indi 218 8686 24 42 sqlite>
使用 Python 的聯接子句
以下 SQLite 示例演示如何使用 python 的聯接子句 -
import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving data sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID''' #Executing the query cursor.execute(sql) #Fetching 1st row from the table result = cursor.fetchall(); print(result) #Commit your changes in the database conn.commit() #Closing the connection conn.close()
輸出
[ ('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'), ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'Raja@mymail.com', 'Vishakhapatnam'), ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com', 'Pune'), ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai') ]
廣告