SQLite中有自动增量吗?

发布于 2024-12-11 18:56:16 字数 557 浏览 0 评论 0原文

我正在尝试在 Sqlite3主键的表一个>。我不确定这是否真的可能,但我希望只需要指定其他字段。

例如:

CREATE TABLE people (
  id integer primary key auto increment, 
  first_name varchar(20), 
  last_name varchar(20)
);

然后,当我添加一个值时,我希望只需要做:

INSERT INTO people VALUES ("John", "Smith");

这可能吗?

我在 Windows 7 中的 cygwin 下运行 sqlite3

I am trying to create a table with an auto-incrementing primary key in Sqlite3. I am not sure if this is really possible, but I am hoping to only have to designate the other fields.

For example:

CREATE TABLE people (
  id integer primary key auto increment, 
  first_name varchar(20), 
  last_name varchar(20)
);

Then, when I add a value, I was hoping to only have to do:

INSERT INTO people VALUES ("John", "Smith");

Is this even possible?

I am running sqlite3 under cygwin in Windows 7.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

一刻暧昧 2024-12-18 18:56:16

您可以免费获得一个,称为 ROWID。无论您是否要求,每个 SQLite 表中都存在这一点。

如果包含 INTEGER PRIMARY KEY 类型的列,则该列指向自动 ROWID 列(是其别名)。

正如您所期望的,每当您插入一行时,ROWID(无论您如何称呼它)都会被分配一个值。如果您在 INSERT 上显式分配非 NULL 值,它将获取指定值而不是自动增量。如果在 INSERT 上显式指定 NULL 值,它将获得下一个自动递增值。

另外,您应该尽量避免:

 INSERT INTO people VALUES ("John", "Smith");

 INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");

改为使用。第一个版本非常脆弱 - 如果您在表定义中添加、移动或删除列,则 INSERT 将失败或生成不正确的数据(值位于错误的列中)。

You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.

If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.

ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.

Also, you should try to avoid:

 INSERT INTO people VALUES ("John", "Smith");

and use

 INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");

instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).

画▽骨i 2024-12-18 18:56:16

是的,这是可能的。根据 SQLite 常见问题解答

声明为INTEGER PRIMARY KEY的列将自动增量。

然后,您必须在插入时在该列上传递NULL。示例:

sqlite3 tmp.sqlite 'create table t(id integer primary key, i integer, j integer)'
sqlite3 tmp.sqlite 'insert into t values (NULL, 10, -10), (NULL, 20, -20)'
sqlite3 tmp.sqlite 'select * from t'

输出:

1|10|-10
2|20|-20

在 Ubuntu 23.04、sqlite 3.40.1 上测试。

Yes, this is possible. According to the SQLite FAQ:

A column declared INTEGER PRIMARY KEY will autoincrement.

You then have to pass NULL on that column when inserting. Example:

sqlite3 tmp.sqlite 'create table t(id integer primary key, i integer, j integer)'
sqlite3 tmp.sqlite 'insert into t values (NULL, 10, -10), (NULL, 20, -20)'
sqlite3 tmp.sqlite 'select * from t'

outputs:

1|10|-10
2|20|-20

Tested on Ubuntu 23.04, sqlite 3.40.1.

长伴 2024-12-18 18:56:16

截至今天 - 2018 年 6 月,


以下是 官方 SQLite 文档 关于该主题的内容(粗体和;斜体是我的):

  1. AUTOINCRMENT 关键字会施加额外的 CPU、内存、磁盘空间和
    如果不是严格需要的话,应该避免磁盘 I/O 开销。这是
    通常不需要。

  2. 在 SQLite 中,INTEGER PRIMARY KEY 类型的列是 的别名
    ROWID(WITHOUT ROWID 表中除外)始终是 64 位带符号的
    整数。

  3. 在插入时,如果 ROWID 或 INTEGER PRIMARY KEY 列不是
    显式给定一个值,然后它会自动填充
    未使用的整数,通常比当前最大的 ROWID 大 1
    使用。无论是否自动增量都是如此
    使用了关键字。

  4. 如果 AUTOINCRMENT 关键字出现在 INTEGER PRIMARY KEY 之后,则
    更改自动 ROWID 分配算法以防止重复使用
    数据库生命周期内的 ROWID。换句话说,
    AUTOINCRMENT 的目的是防止重复使用 ROWID
    之前删除的行。

As of today — June 2018


Here is what official SQLite documentation has to say on the subject (bold & italic are mine):

  1. The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
    disk I/O overhead and should be avoided if not strictly needed. It is
    usually not needed.

  2. In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the
    ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed
    integer.

  3. On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not
    explicitly given a value, then it will be filled automatically with an
    unused integer, usually one more than the largest ROWID currently in
    use. This is true regardless of whether or not the AUTOINCREMENT
    keyword is used.

  4. If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that
    changes the automatic ROWID assignment algorithm to prevent the reuse
    of ROWIDs over the lifetime of the database. In other words, the
    purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from
    previously deleted rows.

萌面超妹 2024-12-18 18:56:16

SQLite AUTOINCRMENT 是一个关键字,用于自动递增表中字段的值。我们可以在创建具有特定列名的表时使用 AUTOINCRMENT 关键字自动递增字段值,以自动递增字段值。

关键字 AUTOINCRMENT 只能与 INTEGER 字段一起使用。
语法:

AUTOINCREMENT 关键字的基本用法如下:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

示例如下:
考虑按如下方式创建 COMPANY 表:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

现在,将以下记录插入表 TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

现在选择记录

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only.
Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below:
Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
ID      NAME            AGE     ADDRESS             SALARY
1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00
柳若烟 2024-12-18 18:56:16

你读过这篇文章吗? 如何创建自动增量字段。

INSERT INTO people
VALUES (NULL, "John", "Smith");

始终插入 NULL 作为 id。

Have you read this? How do I create an AUTOINCREMENT field.

INSERT INTO people
VALUES (NULL, "John", "Smith");

Always insert NULL as the id.

我爱人 2024-12-18 18:56:16

不应在 PRIMARY KEY 附近指定 AUTOINCRMENT 关键字。
创建自动增量主键并插入的示例:

$ sqlite3 ex1

CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);

INSERT INTO room(name, home_id) VALUES ('test', 'home id test');

INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');

SELECT * FROM room;

将给出:

1|test|home id test
2|test 2|home id test 2

One should not specify AUTOINCREMENT keyword near PRIMARY KEY.
Example of creating autoincrement primary key and inserting:

$ sqlite3 ex1

CREATE TABLE IF NOT EXISTS room(room_id INTEGER PRIMARY KEY, name VARCHAR(25) NOT NULL, home_id VARCHAR(25) NOT NULL);

INSERT INTO room(name, home_id) VALUES ('test', 'home id test');

INSERT INTO room(name, home_id) VALUES ('test 2', 'home id test 2');

SELECT * FROM room;

will give:

1|test|home id test
2|test 2|home id test 2
风柔一江水 2024-12-18 18:56:16

除了 rowid 之外,您还可以定义自己的自增字段,但不建议这样做。当我们使用自动增加的 rowid 时,这总是一个更好的解决方案。

AUTOINCRMENT 关键字会施加额外的 CPU、内存、磁盘空间和
磁盘 I/O 开销,如果不是严格需要的话应该避免。这是
通常不需要。

请阅读此处了解详细信息。

Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.

The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed.

Read here for detailed information.

泼猴你往哪里跑 2024-12-18 18:56:16

你所做的是正确的,但是“自动增量”的正确语法应该没有空格:(

CREATE TABLE people (id integer primary key autoincrement, first_name string, last_name string);

另请注意,我将你的 varchar 更改为字符串。那是因为 SQLite 在内部将 varchar 转换为字符串,所以为什么要麻烦呢?)

然后你的insert 应该在 SQL 语言中尽可能标准:

INSERT INTO people(id, first_name, last_name) VALUES (null, 'john', 'doe');

虽然确实,如果您省略 id,它会自动递增和分配,但我个人不喜欢依赖将来可能会改变的自动机制。

关于自动增量的注释:虽然,正如许多人指出的那样,SQLite 人员不推荐它,但我不喜欢在不使用自动增量的情况下自动重用已删除记录的 id。换句话说,我希望已删除记录的 ID 永远不会再次出现。

华泰

What you do is correct, but the correct syntax for 'auto increment' should be without space:

CREATE TABLE people (id integer primary key autoincrement, first_name string, last_name string);

(Please also note that I changed your varchars to strings. That's because SQLite internally transforms a varchar into a string, so why bother?)

then your insert should be, in SQL language as standard as possible:

INSERT INTO people(id, first_name, last_name) VALUES (null, 'john', 'doe');

while it is true that if you omit id it will automatically incremented and assigned, I personally prefer not to rely on automatic mechanisms which could change in the future.

A note on autoincrement: although, as many pointed out, it is not recommended by SQLite people, I do not like the automatic reuse of ids of deleted records if autoincrement is not used. In other words, I like that the id of a deleted record will never, ever appear again.

HTH

墨洒年华 2024-12-18 18:56:16

我知道这个答案有点晚了。
我这个答案的目的是供大家参考,如果他们现在或将来在 SQLite 上遇到这种类型的挑战并且遇到困难时。

现在,回头看看你的查询,它应该是这样的。

CREATE TABLE people (id integer primary key autoincrement, first_name varchar(20), last_name varchar(20));

它对我有效。像这样,

“在此处输入图像描述”"

如果您正在使用 SQLite,我建议您查看 数据库浏览器对于 SQLite。也适用于不同的平台。

I know this answer is a bit late.
My purpose for this answer is for everyone's reference should they encounter this type of challenge with SQLite now or in the future and they're having a hard time with it.

Now, looking back at your query, it should be something like this.

CREATE TABLE people (id integer primary key autoincrement, first_name varchar(20), last_name varchar(20));

It works on my end. Like so,

enter image description here

Just in case you are working with SQLite, I suggest for you to check out DB Browser for SQLite. Works on different platforms as well.

我的奇迹 2024-12-18 18:56:16

在 SQLite 中,您可以使用或不使用 AUTOINCRMENT 进行自动增量,如下所示。 *AUTOINCRMENT 必须与 INTEGER PRIMARY KEY 一起使用,否则会出现是错误的:

CREATE TABLE person (
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  name TEXT           -- ↑↑↑↑↑↑↑↑↑↑↑↑↑
);
CREATE TABLE person (
  id INTEGER PRIMARY KEY, -- No AUTOINCREMENT
  name TEXT
);

并且,AUTOINCRMENT可以避免重用已删除的数字,除非明确指定它们,而没有AUTOINCRMENT则不能根据文档。 *我的问题我的回答解释AUTOINCRMENT和没有AUTOINCRMENT之间的区别。

In SQLite, you can auto-increment with and without AUTOINCREMENT as shown below. *AUTOINCREMENT must be used with INTEGER PRIMARY KEY otherwise there is error:

CREATE TABLE person (
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  name TEXT           -- ↑↑↑↑↑↑↑↑↑↑↑↑↑
);
CREATE TABLE person (
  id INTEGER PRIMARY KEY, -- No AUTOINCREMENT
  name TEXT
);

And, AUTOINCREMENT can avoid to reuse the deleted numbers unless explicitly specifying them while no AUTOINCREMENT cannot according to the doc. *My question and my answer explain the difference between AUTOINCREMENT and no AUTOINCREMENT.

烟酒忠诚 2024-12-18 18:56:16

SQLite中,您可以在定义表时使用INTEGER PRIMARY KEY AUTOINCRMENT关键字创建自动递增主键

示例:

CREATE TABLE people (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    first_name varchar(20), 
    last_name varchar(20)
);

如果没有“AUTOINCRMENT”,SQLite仍会自动递增INTEGER PRIMARY KEY,但它可能会重用已删除行的 ID,这可能会导致问题。

In SQLite, you can create an auto-incrementing primary key by using the INTEGER PRIMARY KEY AUTOINCREMENT keyword when defining a table.

Example:

CREATE TABLE people (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    first_name varchar(20), 
    last_name varchar(20)
);

Without "AUTOINCREMENT", SQLite will still increment the INTEGER PRIMARY KEY automatically, but it could reuse IDs of deleted rows which can cause problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文