SQLite多列唯一约束允许重复

时间:2017-06-21 18:10:56

标签: mysql sqlite

我正在将一个MySQL数据库移植到SQLite,并且SQLite允许重复值存在问题。

CREATE TABLE altnames (
    Prime     CHAR (20),
    Alternate CHAR (20),
    UNIQUE ( Prime, Alternate )
);

CREATE INDEX prime     ON altnames ( Prime     );
CREATE INDEX alternate ON altnames ( Alternate );

CREATE UNIQUE INDEX Combined ON altnames (
    Prime,
    Alternate
);

我正在使用HeidiSQL导出为CSV,并使用SQLiteStudio从那里导入。它将捕获我手动输入的值的重复,但是一旦我从MySQL表中导入数据,它就不会捕获这些值的数据。

该表的目的是链接各种形式的名称。一些样本数据:

"Al","Alan"
"Al","Albert"
"Al","Alfred"
"Al","Allan"
"Al","Allen"
"Al","Alvin"
"Alan","Al"
"Alan","Allan"
"Alan","Allen"
"Albert","Al"
"Albert","Bert"
"Albert","Bertie"
"Alfred","Al"
"Alfred","Fred"
"Alfred","Freddie"
"Alfred","Freddy"
"Allan","Al"
"Allan","Alan"
"Allan","Allen"
"Allen","Al"
"Allen","Alan"
"Allen","Allan"

如果我通过SQLiteStudio接口或以编程方式添加这些项,则会触发约束,但如果我导入它们,则插入这些值将不会触发它。例如,insert into altnames values ('Al', 'Alan')将成功,为我提供两行包含这些值。

编辑:

我发现了一些相当奇怪的行为。根据{{​​3}},ON CONFLICT的默认行为是ABORT,它应该生成SQLITE_CONSTRAINT错误并回滚冲突的数据。我发现,如果我从CSV文件导入数据,它会进行回滚,但不会生成错误。如果我包含ON CONFLICT子句,它会执行回滚并生成错误。 但是,而不是CSV,如果我将数据导出为SQL:

INSERT INTO `altnames` (`Prime`, `Alternate`) VALUES
  ('Al', 'Alan'),
  ('Al', 'Albert'),
  ('Al', 'Alfred'),
  ('Al', 'Allan'),
  ......

并以这种方式导入...然后我得到记录的行为,无论我是否指定ON CONFLICT

1 个答案:

答案 0 :(得分:0)

使用sqlite3命令行工具打开数据库文件并执行:

CREATE TEMP TABLE import(prime, alternate);
.sep ','
.import tabledata.csv import
INSERT OR IGNORE INTO altnames SELECT * FROM import;