【问题标题】:When using an insert into statement in SQL, what element is put in place of the value for an auto increment field在 SQL 中使用 insert into 语句时,用什么元素代替自动增量字段的值
【发布时间】:2025-12-03 17:50:01
【问题描述】:

我创建了 2 个表,它们都以 (pID) 作为主键和外键链接。 pID 是painters 表中的(自动增量字段)主键和painter_specs 表中的外键。如何将painter_specs 中的pID 字段自动填充到painters 表中的相应pID 字段(自动递增)?

这是我的代码

CREATE TABLE painters (
pID     INT NOT NULL AUTO_INCREMENT,
First_Name  CHAR(45) NOT NULL,
Last_Name   CHAR(45) NOT NULL,
Address     CHAR(100) NOT NULL,
primary key (pID));

INSERT INTO painters VALUE (NULL, 'John', 'Doe', '123 Markt St Manassas VA     20021');
INSERT INTO painters VALUE (NULL, 'Jane', 'Smith', '342 Water St.    Centreville VA 20121');
INSERT INTO painters VALUE (NULL, 'Mike', 'Williams', '390 Bank Ave Fairfax     VA 20201');

CREATE TABLE painter_specs (
pID     FOREIGN KEY REFERENCES painters(pID);
Title   CHAR(100) NOT NULL,
Date    DATE NOT NULL,
Painter CHAR(90) NOT NULL,
);

INSERT INTO painter_specs VALUE(NULL, 'Morning Mist', '10/10/2015',     'Beautiful painting about mist', 'John Doe');
INSERT INTO painter_specs VALUE(NULL, 'Evening Shadows', '10/12/2015', 'Beautiful painting about shadows', 'John Doe');
INSERT INTO painter_specs VALUE(NULL, 'Afternoon Thoughts', '10/11/2015', 'Beautiful painting about memories', 'Jane Smith');

使用 insert into 语句,我目前有 NULL 代替由painters 表自动填充到painter_specs 表中的值。

【问题讨论】:

  • 答案可能是特定于编程语言的,因为不同的 sql 库有自己的方法来检索插入行的主键。此外,提及您正在使用的数据库会很有帮助。
  • 你在使用 MySQL 吗?

标签: sql


【解决方案1】:

要将值插入painters 表,请使用以下命令:

INSERT INTO painters (First_Name,Last_Name, Address) VALUES
('John', 'Doe', '123 Markt St Manassas VA     20021'),
( 'Jane', 'Smith', '342 Water St.    Centreville VA 20121'),
('Mike', 'Williams', '390 Bank Ave Fairfax     VA 20201');

一旦数据库填充了painters 表中的pID 列,请将下面painter_specs 表的插入语句中的[pID] 替换为pID 行引用作为@987654328 的一部分@ - 例如1, 2, 3, etc.

INSERT INTO painter_specs (pID, Title, Date, Painter) VALUES 
([pID], 'Morning Mist', '10/10/2015',     'Beautiful painting about mist', 'John Doe'),
([pID], 'Evening Shadows', '10/12/2015', 'Beautiful painting about shadows', 'John Doe'),
([pID], 'Afternoon Thoughts', '10/11/2015', 'Beautiful painting about memories', 'Jane Smith');

【讨论】:

  • 我试试看。谢谢
  • 根据我的 INSERT INTO Painters 声明,我似乎收到一条错误消息,指出“列数与值数不匹配”。我认为这是因为 Painters 表有 4 个必填字段,而我试图仅插入 3 个值。
  • 我不得不对更多代码进行额外的更改,但它确实有效。谢谢