简体   繁体   English

用键插入Android数据库

[英]Inserting into android database with keys

So I want to have an integer ID primary field which autoincrements. 因此,我想拥有一个自动递增的整数ID主字段。 Then I also want another key with a text field. 然后,我还想要另一个带有文本字段的键。 Two entries cannot have the same ID nor can they have the same text field. 两个条目不能具有相同的ID,也不能具有相同的文本字段。 The problem is that if the ID's are different but the text fields the same, I still don't want them to be inserted. 问题是,如果ID不同但文本字段相同,我仍然不希望插入它们。 Unfortunately creating a table with two primary keys means that it CAN be inserted. 不幸的是,创建具有两个主键的表意味着可以将其插入。 Is there anyway to express this besides two primary keys? 无论如何,除了两个主键之外,还有其他表达方式吗?

A table can have only one primary key. 一个表只能有一个主键。 When you write 当你写

CREATE TABLE T1 ... PRIMARY KEY (A, B)

you're not actually creating two primary keys, but rather a single composite (ie multi-column) primary key. 您实际上并不是在创建两个主键,而是一个单一的复合(即多列)主键。 In this case, it means that two rows cannot share the same values of both A and B . 在这种情况下,这意味着两行不能共享A和B的相同值。

If you need both A and B to be unique by themselves, then you need to use a UNIQUE constraint (or, alternatively, a unique index). 如果您需要A和B本身都唯一,那么您需要使用UNIQUE约束 (或者,唯一索引)。

From the SQLite documentation : SQLite文档中

A UNIQUE constraint is similar to a PRIMARY KEY constraint, except that a single table may have any number of UNIQUE constraints. UNIQUE约束与PRIMARY KEY约束相似,除了单个表可以具有任意数量的UNIQUE约束。 For each UNIQUE constraint on the table, each row must contain a unique combination of values in the columns identified by the UNIQUE constraint. 对于表上的每个UNIQUE约束,每一行都必须在由UNIQUE约束标识的列中包含值的唯一组合。

For example: 例如:

CREATE TABLE T1 (A INTEGER PRIMARY KEY, B INTEGER UNIQUE ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM