SQLIte如何在列值更改时插入唯一数据

时间:2017-07-05 13:22:40

标签: android sqlite android-sqlite

我在我的应用程序中使用SQLite数据库。我的数据库中有4列 - Student_Name,Student_Enroll,Student_Mob,Student_Address。现在我可以添加新记录当且仅当四列值中的一个不同或所有值都不同时。如果所有列值相同,则不应生成新记录。 你能指导我解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

尽管将列设置为UNIQUE,但在尝试插入新数据时,还需要解决在每列上创建的冲突。

为此,请定义解决冲突的行为:

myfunc

答案 1 :(得分:1)

要强制一组列必须唯一,请添加UNIQUE约束:

create table Students (
 /* ID              INTEGER PRIMARY KEY, */
    Student_Name    TEXT,
    Student_Enroll  TEXT,
    Student_Mob     TEXT,
    Student_Address TEXT,
    UNIQUE (Student_Name, Student_Enroll, Student_Mob, Student_Address)
);

仅当四列中至少有一列具有不同的值时,才允许新行。

使用普通INSERT,尝试插入重复行将导致错误。如果您只是想忽略它,请使用INSERT OR IGNORE:

INSERT OR IGNORE INTO Students ...;

答案 2 :(得分:0)

在“创建数据库”行期间,为每列插入UNIQUE ...以仅插入唯一记录。

答案 3 :(得分:0)

解决方案1:(简单)

将所有列定义为unique

create table TableName (id  integer primary key autoincrement,
Student_Name text not null unique, 
Student_Enroll text not null unique, 
Student_Mob text not null unique);

如果需要,您也可以添加Student_Address

解决方案2:(位复杂)

AND运算符与WHERE子句

一起使用
INSERT INTO TableName (Student_Name, Student_Enroll, Student_Mob)
SELECT varStudentName, varStudentEnroll, varStudentMob 
WHERE NOT EXISTS(SELECT 1 FROM TableName WHERE Student_Name = varStudentName OR Student_Enroll = varStudentEnroll OR Student_Mob = varStudentMob ); 

//If a record already contains a row, then the insert operation will be ignored.

您可以在the sqlite manual找到更多信息。

直播示例:

  1. 打开SQLite Online
  2. 粘贴以下代码:

    INSERT INTO demo (id,name,hint)
    SELECT 4, 'jQuery', 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML' 
    WHERE NOT EXISTS(SELECT 1 FROM demo WHERE name = 'jQuery' OR hint = 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML' ); 
    
    SELECT * from demo
    
  3. 点击 RUN

  4. 这不会插入第4条记录,如果修改WHERE子句的两个值,则会插入记录。