考虑下表:
CREATE TABLE `FooAttachments` (
`AttachmentId` bigint(20) NOT NULL AUTO_INCREMENT,
`FooId` bigint(20) NOT NULL,
`AttachmentPath` varchar(100) NOT NULL,
PRIMARY KEY (`AttachmentId`),
KEY `IX_FooAttachment_FooBase` (`FooId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf16
如果我使用以下语句在此表中插入一行,则会创建一行,并且AI字段会生成一个值。
INSERT INTO FooAttachments (FooId, AttachmentPath) VALUES (1, 'test path');
但是,当我尝试使用INSERT INTO SELECT语句时,我收到一个错误:
INSERT INTO FooAttachments
SELECT 1 AS FooId, 'test path' as AttachmentPath;
我得到的错误是:#1136 - 列数与第1行的值计数不匹配
我知道我没有指定AttachmentId列,但我也没有在INSERT INTO ... VALUES语句中这样做,而且那个工作正常。更重要的是,我不想为该列指定值,它应该是自动生成的。
我应该如何编写第二个查询?
答案 0 :(得分:2)
您必须为列命名
INSERT INTO FooAttachments (FooId, AttachmentPath)
SELECT 1 AS FooId, 'test path' as AttachmentPath;
答案 1 :(得分:0)
触发自动增量的方法是插入null。像这样:
INSERT INTO FooAttachments
SELECT NULL AS AttachmentID, 1 As FooId, 'test path' as AttachmentPath;