SQLite中的多个唯一列
我正在尝试创建一个表格,要求它不允许有三列的值是相同的行。
当我在Python中使用SQLLite创建这个表时,我用的是下面的代码,但我几乎没有得到任何结果。通常在写入两条记录后就停止了,所以显然有某些东西认为这些记录是重复的。
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这四个字段的值是相同的。
有没有人能帮我解决这个问题呢?
谢谢!
2 个回答
0
你不是在找 UNIQUE,而是在找 PRIMARY KEY。 当你设置 PRIMARY KEY(ownerID1, ownerID2, accountKey, argID1)时,这四个值一起就构成了一行的索引。
这意味着,如果你写入一行数据,这四个值和已有的一行相同,那么它会覆盖掉那一行。因此,这四个值的每一种组合只能出现一次。
而 UNIQUE 则意味着这四个值中的每一个只能使用一次。
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