2011-01-05 72 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个值中的每一个只能使用一次。