【问题标题】:Multiple Unique Columns in SQLiteSQLite 中的多个唯一列
【发布时间】:2011-01-05 13:07:30
【问题描述】:

我正在尝试创建一个表,我需要它来不允许 3 个字段相同的行。

当我使用 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 相同的记录。

谁能帮我解决这个问题?

谢谢!

【问题讨论】:

  • 它通常在写入 2 条记录后停止,所以显然有些东西认为它是重复的。 - 为什么这么明显?插入失败时会收到什么错误消息?
  • 您没有在任何列上指定NOT NULL,因此您可能会得到违反唯一约束的空值。插入失败后的数据是什么样的?

标签: python sql sqlite unique-key


【解决方案1】:

我不确定是什么问题。它在这里工作正常:

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

【讨论】:

    【解决方案2】:

    您不是在寻找 UNIQUE,而是在寻找 PRIMARY KEY。当您设置 PRIMARY KEY (ownerID1, ownerID2, accountKey, argID1) 时,这 4 个值一起是行索引。 这意味着,如果您使用这 4 个值等于现有值写入一个新行,它将覆盖该行。因此,这 4 个值的每个组合只能存在一次。

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

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 1970-01-01
      • 2013-01-09
      • 2016-11-30
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2011-07-12
      相关资源
      最近更新 更多