2017-05-06 67 views
0

我已經在python中使用sqlite創建了2個表,並且我認爲我做了正確的操作,以便它們與外鍵鏈接。如果我的代碼是正確的,是否有人知道如何獲取值。下表中的代碼以及獲取不返回任何值的代碼。如何使用sqlite從2個表中獲取值

c.execute("SELECT value AND wage FROM classes, yourplayers WHERE Firstname=? AND Secondname=?", (self.Seller_Firstname, self.Seller_Lastname)) 


c.execute("CREATE TABLE IF NOT EXISTS classes(class INT NOT NULL, wage INT NOT NULL, value INT NOT NULL)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (1, 1000, 5000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (2, 5000, 1000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (3, 10000, 15000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (4, 25000, 20000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (5, 50000, 25000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (6, 100000, 35000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (7, 150000, 50000000)") 
c.execute("INSERT INTO classes(class, wage, value) VALUES (8, 225000, 80000000)") 
c.execute("SELECT * FROM classes") 
conn.commit() 
print(c.fetchall()) 

c.execute('DROP TABLE IF EXISTS yourplayers') 
c.execute('CREATE TABLE yourplayers(PlayerId INT PRIMARY KEY NOT NULL, Firstname VARCHAR(10) NOT NULL, Secondname VARCHAR(10) NOT NULL, contract INT NOT NULL, rating INT NOT NULL, class INT NOT NULL, morale INT NOT NULL, FOREIGN KEY (class) REFERENCES classes(class))') 
x = 1 
for x in range(20): 
    FN = open("firstnames", "r") 
    FNames = FN.read() 
    listF = FNames.split('\n') 
    y = randint(0,55) 
    N1 = listF[y] 
    N1 = str(N1) 
    SN = open("lastnames", "r") 
    SNames = SN.read() 
    listS = SNames.split('\n') 
    z = randint(0, 9) 
    N2 = listS[z] 
    N2 = str(N2) 
    c.execute("INSERT INTO yourplayers(PlayerId, Firstname, Secondname, contract, rating, class, morale) VALUES (? , ?, ?, 2, 55, 1, 55)", 
       (x, N1, N2)) 
    x = x+1 
c.execute('SELECT * FROM yourplayers') 
conn.commit() 

每個段落是在一個單獨的功能,但香港專業教育學院去除不相關的代碼

回答

1

一個foreign key constraint僅僅是一個約束,即,它阻止你插入這將違反約束的數據。

外鍵約束對查詢沒有影響;如果您想通過這些值連接表,你還是得寫加盟:

SELECT value, wage  -- no AND here 
FROM classes 
JOIN yourplayers USING (class) 
WHERE Firstname=? 
    AND Secondname=?; 
+0

好,謝謝掃清事情了,我的印象是,外鍵使這一切成爲可能的,但感謝你的答案我會做一個加入。 – maxpepsi