我有一个sqlite表,其中有两列,例如name和surname。我希望name和surname必须不同,而不仅仅是name。
我的表格代码是
private static final String MAKE_TABLE_NAME_SURNAME = "CREATE TABLE " +
TABLE_DISEASE_SEMPTOM + "(" + KEY_DSID " INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT, " + SURNAME + " TEXT) ";
我不能使用
private static final String MAKE_TABLE_NAME_SURNAME = "CREATE TABLE " +
TABLE_DISEASE_SEMPTOM + "(" + KEY_DSID " INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT UNIQUE, " + SURNAME + " TEXT UNIQUE) ";
因为如果我使用此代码,则无法添加相同的名称但不同的姓氏或相同的姓氏但不同的名字。如果只有两个相同,怎么能忽略呢?
答案 0 :(得分:1)
此检查在服务器/应用程序一侧进行。 (在尝试将变量插入数据库之前,先检查一下变量)
答案 1 :(得分:1)
我相信以下是您想要的:-
private static final String MAKE_TABLE_NAME_SURNAME = "CREATE TABLE " +
TABLE_DISEASE_SEMPTOM + "(" + KEY_DSID " INTEGER PRIMARY KEY AUTOINCREMENT," +
NAME + " TEXT, " + SURNAME + " TEXT, UNIQUE(" + NAME + "," + SURNAME +")) ";
也就是说,您正在定义名称列和姓氏列的组合作为UNIQUE约束。
例如考虑:-
DROP TABLE IF EXISTS TABLE_DISEASE_SEMPTOM;
CREATE TABLE IF NOT EXISTS TABLE_DISEASE_SEMPTOM (KEY_DSID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, UNIQUE(NAME,SURNAME));
INSERT INTO TABLE_DISEASE_SEMPTOM (NAME,SURNAME) VALUES('Fred','Bloggs'),('Fred','Smith'),('Mary','Smith'),('Jane','Doe');
INSERT OR IGNORE INTO TABLE_DISEASE_SEMPTOM (NAME,SURNAME) VALUES('Fred','Bloggs'); -- will not be inserted as duplicate
SELECT * FROM TABLE_DISEASE_SEMPTOM;
前四个插入工作,最后一个(靠自己)被忽略(因为它是重复的)。 因此,最终查询产生:-
日志为:-
INSERT INTO TABLE_DISEASE_SEMPTOM (NAME,SURNAME) VALUES('Fred','Bloggs'),('Fred','Smith'),('Mary','Smith'),('Jane','Doe')
> Affected rows: 4
> Time: 0.117s
INSERT OR IGNORE INTO TABLE_DISEASE_SEMPTOM (NAME,SURNAME) VALUES('Fred','Bloggs')
> Affected rows: 0
> Time: 0.117s
即最后一次插入没有插入行