简体   繁体   English

SQL 如何根据另一个值自动增加一个值

[英]SQL how to auto increment a value depending on another value

I am creating a program where I am using a SQL Database, but I have a problem on how to solve the following problem.我正在创建一个程序,我正在使用 SQL 数据库,但我对如何解决以下问题有疑问。

I have a table named Warehouse where I have WarehouseID and a WarehouseName.我有一个名为 Warehouse 的表,其中有 WarehouseID 和 WarehouseName。

Then, I created another table named Aisle where I have WarehouseID (which should be the same field as before) and AisleID and AisleName.然后,我创建了另一个名为 Aisle 的表,其中包含 WarehouseID(应该与之前的字段相同)以及 AisleID 和 AisleName。

So WarehouseID and AisleID can be 1, 2, 3... But what I want is that when I select WarehouseID = 1 to create a new AisleID, the database should be able to notice which is the last number of AisleID for WarehouseID = 1 and add an autoincrement.所以 WarehouseID 和 AisleID 可以是 1, 2, 3... 但是我想要的是当我 select WarehouseID = 1 来创建一个新的 AisleID 时,数据库应该能够注意到 WarehouseID = 1 的最后一个 AisleID并添加一个自动增量。

So, can be multiple AisleID with the same value but only a WarehouseID with one unique value.因此,可以是多个具有相同值的 AisleID,但只能是具有一个唯一值的 WarehouseID。

How can I do that in SQL?我该如何在 SQL 中做到这一点?

Thanks and Kind Regards感谢和亲切的问候

This query:这个查询:

SELECT COALESCE(MAX(AisleID), 0) + 1
FROM Aisle
WHERE WarehouseID = 1

returns the new AisleID that you want to insert in the table Aisle .返回要在表Aisle中插入的新AisleID
But what value do you want for AisleName ?但是您想要AisleName的值是多少?
If AisleName is the same for all rows in Aisle with the same WarehouseID you could use MAX(AisleName) , or if it's not you must supply that value.如果AisleName对于Aisle中具有相同WarehouseID的所有行都相同,则可以使用MAX(AisleName) ,或者如果不是,则必须提供该值。

So you can do this:所以你可以这样做:

INSERT INTO Aisle(AisleID, AisleName, WarehouseID)
SELECT COALESCE(MAX(AisleID), 0) + 1, MAX(AisleName), ?
FROM Aisle
WHERE WarehouseID = ?

Replace ?更换? with the value of WarehouseID that you want the row to have.具有您希望该行具有的WarehouseID的值。
Also replace MAX(AisleName) with the new value of AisleName if you want it to be different than the previous rows, or if it is the first row with that WarehouseID .如果您希望它与之前的行不同,或者如果它是具有该WarehouseID的第一行,也将MAX(AisleName)替换为AisleName的新值。

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

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