2011-01-05 29 views
0

我想創建一個表,我需要它不允許3個字段相同的行。SQLite中的多個唯一列

當我使用SQLLite在Python中創建表時,我使用後面的,但是我幾乎沒有得到任何結果。它通常會在寫入2條記錄後停止,所以有些事情顯然相信它是重複的。

CREATE TABLE CorpWalletJournal (
    date INT, 
    refID INT, 
    refTypeID INT, 
    ownerName1 TEXT, 
    ownerID1 INT, 
    ownerName2 TEXT, 
    ownerID2 INT, 
    argName1 TEXT, 
    argID1 ID, 
    amount INT, 
    balance INT, 
    reason TEXT, 
    accountKey INT, 

    UNIQUE (ownerID1, ownerID2, accountKey, argID1) 
); 

所以,我想數據庫不允許記錄,其中ownerID1,ownerID2,accountKey和argID1是相同的。

任何人都可以幫助我呢?

謝謝你!

+0

*它通常會在寫入2條記錄後停止,所以有些東西顯然相信它是重複的。* - 爲什麼這很明顯?插入失敗時會得到什麼錯誤信息? – 2011-01-05 13:12:51

+1

你沒有在任何列上指定NOT NULL,所以你可能會得到空值違反唯一約束。插入失敗後數據看起來如何? – Hollister 2011-01-05 13:39:45

回答

2

我不確定是什麼問題。它的工作原理在這裏罰款:

import sqlite3 

# connect to memory-only database for testing 
con = sqlite3.connect('') 
cur = con.cursor() 

# create the table 
cur.execute(''' 
CREATE TABLE CorpWalletJournal (
    date INT, refID INT, refTypeID INT, ownerName1 TEXT, 
    ownerID1 INT, ownerName2 TEXT, ownerID2 INT, argName1 TEXT, 
    argID1 ID, amount INT, balance INT, reason TEXT, accountKey INT, 
    UNIQUE (ownerID1, ownerID2, accountKey, argID1) 
); 
''') 
con.commit() 

insert_sql = '''INSERT INTO CorpWalletJournal 
(date, refID, refTypeID, ownerName1, ownerID1, ownerName2, ownerID2, 
argName1, argID1, amount, balance, reason, accountKey) 
VALUES 
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''' 

## create 5 rows changing only argID1 - it works: 
for argid in xrange(5): 
    cur.execute(insert_sql, (1, 1, 1, 'a', 1, 'a', 1, 'a', argid, 1, 1, 'a', 1)) 
con.commit() 

# now try to insert a row that is already there: 
cur.execute(insert_sql, (1, 1, 1, 'a', 1, 'a', 1, 'a', 0, 1, 1, 'a', 1)) 

我從最後一行得到的錯誤是:

Traceback (most recent call last): 
    File "teststdio.py", line 41, in <module> 
    cur.execute(insert_sql, (1, 1, 1, 'a', 1, 'a', 1, 'a', 0, 1, 1, 'a', 1)) 
sqlite3.IntegrityError: columns ownerID1, ownerID2, accountKey, argID1 
    are not unique 
0

你是不是想找唯一的,但是對於主鍵。當你設置PRIMARY KEY(ownerID1,ownerID2,accountKey,argID1)時,這4個值一起是行索引。 這意味着,如果您使用與現有值相等的4個值編寫新行,它將覆蓋該行。因此,4個值的每個組合只能存在一次。

另一方面,UNIQUE意味着4個值中的每一個只能使用一次。