【问题标题】:sqlite multiple unique isn't worksqlite 多个唯一性不起作用
【发布时间】:2013-01-09 17:48:19
【问题描述】:

我有一张桌子:

CREATE TABLE IF NOT EXISTS city_recent
            (_id INTEGER PRIMARY KEY AUTOINCREMENT,
            city_id INTEGER NOT NULL,
            language BOOL NOT NULL,
            type BOOL NOT NULL,
            FOREIGN KEY (city_id) REFERENCES city(_id),
            UNIQUE(city_id, type) ON CONFLICT IGNORE)

但唯一不起作用:

【问题讨论】:

    标签: sqlite unique-constraint


    【解决方案1】:

    我已经测试了您的代码,它按预期工作(测试如下所示)。最有可能发生的事情是表是在没有UNIQUE 约束的情况下预先创建的。尝试删除IF NOT EXISTS 以确认。

    >>> import sqlite3
    >>> con = sqlite3.connect(':memory:')
    >>> con.execute('''CREATE TABLE IF NOT EXISTS city_recent
    ...             (_id INTEGER PRIMARY KEY AUTOINCREMENT,
    ...             city_id INTEGER NOT NULL,
    ...             language BOOL NOT NULL,
    ...             type BOOL NOT NULL,
    ...             FOREIGN KEY (city_id) REFERENCES city(_id),
    ...             UNIQUE(city_id, type) ON CONFLICT IGNORE);''')
    <sqlite3.Cursor object at 0x01298FA0>
    >>> con.execute('insert into city_recent(city_id,language,type) values (0,0,1);')
    <sqlite3.Cursor object at 0x0129F120>
    >>> con.execute('insert into city_recent(city_id,language,type) values (0,0,1);')
    <sqlite3.Cursor object at 0x01298FA0>
    >>> con.execute('select * from city_recent').fetchall()
    [(1, 0, 0, 1)] # -> note that there is only one row in the table
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多