简体   繁体   English

如何在查询中将数据插入没有 ID 的表中?

[英]How to insert data into a table without Id in query?

I would like to know how use insert command in query without knowing the Id my table consists of Id ||我想知道如何在不知道 Id 我的表由 Id || 组成的查询中使用插入命令Dollars ||美元 || UserName and my table name is creds UserName 和我的表名是 creds

I've tried doing insert commands but i cant figure it out我试过做插入命令,但我想不通

I would just like to know how to get Id without knowing how many columns there are so say there are 3 columns but I dont know that how can I make a new column.我只想知道如何在不知道有多少列的情况下获取 Id,所以说有 3 列,但我不知道如何创建一个新列。

ID is Primary Key ID 是主键

INSERT INTO creds VALUES(Id, 50, 'UserName')

You should always list the columns when doing an insert :执行insert时,您应该始终列出列:

INSERT INTO creds (dollars, username)
     VALUES (50, 'UserName');

If you want to list the id column, use DEFAULT :如果要列出id列,请使用DEFAULT

INSERT INTO creds (id, dollars, username)
     VALUES (DEFAULT, 50, 'UserName');

For insert actually, you don't need to know the Id实际上,对于插入,您不需要知道 Id

INSERT INTO creds (Id, Dollars, Username) VALUES(50, 2000, 'UserName')

If Id is Identity then you must not include it in the insert:如果 Id 是 Identity 那么你不能将它包含在插入中:

INSERT INTO creds (Dollars, Username) VALUES(2000, 'UserName')

You would need Id (probably primary key) only if you are updating table:只有在更新表时才需要 Id(可能是主键):

Update creds set username = 'New Username' where Id = 50

If "Id" column(field)" is auto-incrementable , "Id" and the value are not needed for "INSERT" query :如果"Id" column(field)"自动递增的,则"INSERT" 查询不需要"Id"该值

                -- Don't need "Id" and the value
INSERT INTO creds (Dollars, Username) VALUES(2000, 'UserName')

If "Id" column(field)" is not auto-incrementable , "Id" and the value are needed for "INSERT" query :如果"Id" column(field)"不是自动递增的,则"INSERT" 查询需要"Id"

                -- Here                       -- Here
INSERT INTO creds (Id, Dollars, Username) VALUES(13, 2000, 'UserName')

It is not a good practice to leave the column name when inserting values in a table.在表中插入值时保留列名不是一个好习惯。 But you can do something like this:但是你可以做这样的事情:

INSERT INTO creds VALUES(
(SELECT max(Id)+1 FROM creds), 50, 'UserName')

If Id is an integer primary key.如果 Id 是整数主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM