MySQL 如何在不指定列名的情况下使用 AUTO_INCREMENT 列向数据库插入新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3493612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert new row to database with AUTO_INCREMENT column without specifying column names?
提问by Misha Moroshko
I have a table with the following columns:
我有一个包含以下列的表格:
id
- INT UNSIGNED AUTO_INCREMENTname
- VARCHAR(20)group
- VARCHAR(20)
id
- INT UNSIGNED AUTO_INCREMENTname
- VARCHAR(20)group
- VARCHAR(20)
I know that I can add a row like this:
我知道我可以添加这样的一行:
INSERT INTO table_name (name, group) VALUES ('my name', 'my group')
I wonder if there is a way to add a row without specifying the column names, like when there is no AUTO_INCREMENT column ?
我想知道是否有一种方法可以在不指定列名的情况下添加行,就像没有 AUTO_INCREMENT 列一样?
回答by Ike Walker
For some databases, you can just explicitly insert a NULL
into the auto_increment
column:
对于某些数据库,您只需将 a 显式插入NULL
到auto_increment
列中:
INSERT INTO table_name VALUES (NULL, 'my name', 'my group')
回答by Frank Heikens
Even better, use DEFAULTinstead of NULL. You want to store the default value, not a NULL that might trigger a default value.
更好的是,使用DEFAULT而不是 NULL。您想要存储默认值,而不是可能触发默认值的 NULL。
But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schemaand construct the queries you need. There is no need to do it all by hand, SQL can help you out.
但是您最好命名所有列,使用一条 SQL 您可以创建您需要的所有 INSERT、UPDATE 和 DELETE。只需检查information_schema并构建您需要的查询。无需手动完成所有操作,SQL 可以帮助您。
回答by HLGEM
Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.
只需添加列名,是的,您可以使用 Null 代替,但永远不要在任何插入中使用列名是一个非常糟糕的主意。