【问题标题】:SQLite: double primary key and autoincrementSQLite:双主键和自动增量
【发布时间】:2013-04-18 11:43:58
【问题描述】:

我正在尝试定义一个两行主键,这样 第二列为每个人自动递增 第一行的值。

例如我们会:

X Y
A 1
A 2
A 3
A 4
A 5
B 1
B 2
B 3
C 1
D 1
E 1
E 2

我想做一个:

create table t (x text, y integer autoincrement) primary key (x, y);

但是我从 SQLite 收到一个错误,说我在“自动增量”附近有一个错误。我能做些什么? (只要我能让它工作,即使是一个整数值 x 也可以)。

然后我想通过以下方式获得上述值:

insert into t (x) values ('A');
insert into t (x) values ('A');
insert into t (x) values ('A');
insert into t (x) values ('A');
insert into t (x) values ('A');
insert into t (x) values ('B');
insert into t (x) values ('B');
insert into t (x) values ('B');
insert into t (x) values ('C');
insert into t (x) values ('D');
insert into t (x) values ('E');
insert into t (x) values ('E');

谢谢,

杰森定位

【问题讨论】:

  • AUTOINCREMENT 是只能在列约束 PRIMARY KEY 子句中使用的关键字。不过,我对实际问题一无所知。您的问题背后的问题是什么 - 也许可以将问题改造成更简单的问题。

标签: sqlite android-sqlite


【解决方案1】:

如果您的表格中有两次或更多次相同的数字,您将无法自动递增。我知道你想做什么,但不能用自动增量来完成。

但你可以像
创建表t(x text not null, y integer not null) 主键(x, y);

另见:sqlite: multi-column primary key with an auto increment column

【讨论】:

    【解决方案2】:

    您不能从 sqlite 执行此操作。您需要从上层(即您的程序)执行此操作。伪代码如下:

    char current_symbol='A';
    int count=0;
    for(loop all your data)
    {
        if(current_symbol == same text)
        {
          count++;    
        }
        else
        {
          current_symbol = same text;
          count=1;
        }
    
        insert into t (x,y) values ('A', count);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 1970-01-01
      • 2010-10-13
      • 2015-05-11
      • 1970-01-01
      • 2013-05-24
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多