SQLite:防止重复行

时间:2015-03-28 02:09:47

标签: sql database sqlite

CREATE TABLE Permission ( 
    permissionID INTEGER PRIMARY KEY UNIQUE,
    user         INTEGER
    location     INTEGER 
);

我不希望将用户或位置设为UNIQUE,因为我可以拥有包含相同数据的用户的多行,或包含相同数据的多个行。我只是想避免让用户和位置都有一些值,该行重复任意次。

例如:这没关系

permissionID user location
--------------------------
      1        1     2
      2        2     2
      3        2     1

但这不合适:

permissionID user location
--------------------------
      1        1     2
      2        1     2

因为已经存在一行,其中user = 1且location = 2.

如何避免重复?

3 个答案:

答案 0 :(得分:18)

在(用户,位置)上声明唯一约束。

CREATE TABLE Permission (
    permissionID integer primary key,
    user integer not null,
    location integer not null,
    unique (user, location)
);
sqlite> insert into Permission (user, location) values (1, 2);
sqlite> insert into Permission (user, location) values (1, 2);
Error: UNIQUE constraint failed: Permission.user, Permission.location

答案 1 :(得分:2)

第一个选项是在unique constraintuser列上创建location,以避免重复。

Create unique index permission_user_location  on permission (user,location);

否则,如果表中已有重复的行,则需要删除重复的行并创建unique constraint

要删除重复的行,请使用此查询

DELETE
FROM Permission 
WHERE NOT EXISTS 
(
select 1 from 
(
select min(permissionID) as permissionID, user, location
From Permission A
Group by user, location
) B
Where B.permissionID = Permission.permissionID
AND   B.user = Permission.User
AND   B.location = Permission.location 
)

答案 2 :(得分:1)

CREATE TABLE Permission ( 
    permissionID INTEGER PRIMARY KEY UNIQUE,
    user         INTEGER,
    location     INTEGER 
);
CREATE UNIQUE INDEX user_location ON Permission (user,location);