簡體   English   中英

用 Python 鏈接 SQLite 3 中的表

[英]Linking tables in SQLite 3 in Python

我必須創建一個程序,將人們的帳戶詳細信息存儲在 SQLite 3 的表中。其中一列是興趣,這是用戶最喜歡觀看的電影類型。 然后我需要根據該類型向他們推薦電影,所以我需要另一個表來存儲該類型的電影。 唯一的問題是我不知道如何鏈接表格,所以當喜劇是他們最喜歡的類型時,如何輸出類型喜劇中的電影。

這是我添加新用戶的代碼:

    #function for creating a new customer's account
def create_id(username, password, name, address, DoB, gender, interestsUp, recent1, recent2, recent3, recent4, recent5, recent6, recent7, recent8, recent9, recent10):
    #When adding something to a SQLite file, you have to put "" around each item
    c.execute('INSERT INTO userId(username,password,name,address,DoB,gender,interests, recent1, recent2, recent3, recent4, recent5, recent6, recent7, recent8, recent9, recent10) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (username, password, name, address, DoB, gender, interestsUp, recent1, recent2, recent3, recent4, recent5, recent6, recent7, recent8, recent9, recent10))#When adding something thats in a variable you put question marks and the name of the variables in brackets
    conn.commit()

您不應該嘗試將所有數據存儲在一張表中。 您應該為每個主題(例如用戶詳細信息、興趣)使用一個表格,然后表達表格之間的關系。 您可以在設計時使用外鍵執行此操作,這將有助於保持數據清潔,但您還需要在提取數據時定義關系。

下面是一個例子:

表 1:用戶
user_id,用戶名

表 2:User_Details
user_id、密碼、姓名、地址、DoB、性別

表 3:收藏夾
fav_id、user_id、流派

表 4:薄膜
電影 ID、電影名稱、類型

要獲取用戶首選類型的列表,則為:

SELECT Films.film_name
FROM Users
INNER JOIN Favourites ON Users.user_id = Favourites.user_id
INNER JOIN Films ON Favourites.genre = Films.genre
WHERE user_id = ?

這里幾乎所有的過濾都是由 INNER JOIN 完成的。 這將連接表,但只返回存在於兩個表中的結果。 這意味着如果用戶尚未提交任何首選項,則不會為該用戶返回任何結果。 ON指令告訴數據庫關系是什么。

輸出將是與用戶喜歡的任何類型相關的電影列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM