问题描述
我正在尝试使用此语法代码将值插入表中,但它显示“列数与第 1 行的值数不匹配”。
INSERT INTO users (userid,name,username,address,city,state,zip,password)
VALUES ('Bonnie Buntcake','bbunt','6709 Wonder Street','Wonderbread','OH','46105','eclectic');
INSERT INTO users (userid,password)
VALUES ('Sam Smarf','ssmarf','356 A Street','Beefy','PA',19943,'swimming');
INSERT INTO users (userid,password)
VALUES ('Wendy Grog','wgrog','900 Star Street','Mary','MD',21340,'wells');
INSERT INTO users (userid,password)
VALUES ('Joe Jogger','jjogger','183713 N north Street','norther','WV',51423,'tarts');
我还将表格更改为 NOT NULL:
ALTER TABLE locations MODIFY type INT NOT NULL;
ALTER TABLE locations MODIFY description CHAR NOT NULL;
ALTER TABLE locations MODIFY lng INT NOT NULL;
ALTER TABLE locations MODIFY lat INT NOT NULL;
ALTER TABLE users MODIFY userid INT NOT NULL;
ALTER TABLE users MODIFY name CHAR NOT NULL;
ALTER TABLE users MODIFY username CHAR NOT NULL;
ALTER TABLE users MODIFY password CHAR NOT NULL;
ALTER TABLE photograph MODIFY photoid INT NOT NULL;
ALTER TABLE photograph MODIFY locationid INT NOT NULL;
Here's a screenshot of the workbench tables
解决方法
您的 userid
列似乎是一个自动递增的主键,但我没有在 Workbench 图像中看到选中的 AI
属性。
将 AUTO_INCREMENT
属性添加到 userid
。
ALTER TABLE users MODIFY userid INT NOT NULL PRIMARY KEY AUTO_INCREMENT;
此外,您的某些 (1)
列没有字符长度或 CHAR
长度。它们需要比这更长,否则它们将被截断。我建议改用 VARCHAR()
,并具有适当的最大长度。
-- For a 32 character username
ALTER TABLE users MODIFY username VARCHAR(32);
-- Allow a large size for passwords - hashing algorithms might make them long
ALTER TABLE users MODIFY password VARCHAR(128);
最后到列数不匹配...这是因为您在 userid
的列列表中包含了 INSERT
但没有在 VALUES()
中包含它的值列表。列列表有 8 列,但 VALUES()
只有 7 个值。有两种解决方案。
或者从列列表中省略 userid
,以便 MySQL 用递增值自动填充它:
-- Leave `userid` out
INSERT INTO users (name,username,address,city,state,zip,password)
VALUES ('Bonnie Buntcake','bbunt','6709 Wonder Street','Wonderbread','OH','46105','eclectic');
或者将 userid
留在里面,但在 NULL
列表中提供一个 VALUES()
。 MySQL 还将用自动递增值替换 NULL
-- Add a NULL to `VALUES()` in the position of `userid`
INSERT INTO users (userid,name,password)
VALUES (NULL,'Bonnie Buntcake','eclectic');