我如何获得自动递增值

How I can get an auto incremented value

我这里有一个 table 对应于客户的订单。我使用 AUTO_INCREMENT 来确定订单的 ID。我有这个 SQL 代码到 orders table:

CREATE TABLE IF NOT EXISTS `orders` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `customer_name` varchar(500) NOT NULL,
  `order_total_price` decimal(20, 2) NOT NULL,
  `order_date` varchar(100) NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB

我需要用外键 order_id 将该订单的每个产品插入另一个 table 以指定该产品属于哪个订单。 purchased_products table 的 SQL 代码是:

CREATE TABLE IF NOT EXISTS `purchased_products` (
  `order_id` int (11) NOT NULL,
  FOREIGN KEY (`order_id`) REFERENCES orders(`order_id`),
  `product_name` varchar(500) NOT NULL,
  `product_price` decimal(20, 2) NOT NULL,
  `product_quantity` int(11) NOT NULL,
  PRIMARY KEY (`order_id`)
) 

当用户买东西的时候,我用这个把数据插入orders table:

INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";

这是我的问题。我需要在 purchased_products table 中插入生成订单 ID 的产品:

INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('*/The ID of the order need to goes here*/', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";

这让我很头疼。我真的不知道该怎么做。这应该通过不同的方式来完成?如何将订单 ID 关联到属于它的产品?

您可以使用@@IDENTITY

获取最后插入的主键值

这是 MSDN 文章:https://msdn.microsoft.com/en-us/library/ms187342.aspx

USE AdventureWorks2012;
GO
--Display the value of LocationID in the last row in the table.
SELECT MAX(LocationID) FROM Production.Location;
GO
INSERT INTO Production.Location (Name, CostRate, Availability, ModifiedDate)
VALUES ('Damaged Goods', 5, 2.5, GETDATE());
GO

SELECT @@IDENTITY AS 'Identity';
GO
--Display the value of LocationID of the newly inserted row.
SELECT MAX(LocationID) FROM Production.Location;
GO

我还建议将语句包装在 TRANSACTION 中,以便在发生任何错误时可以回滚。

您可以使用 SCOPE_IDENTITY() 检索您在当前 sql 会话中插入的最后一个身份。

这是另一个问题,对所有差异进行了很好的描述:

identity scope Question

正如其他人评论的那样,它取决于 RDBMS。在 Oracle 中,您通常使用 sequences。您创建序列并将其存储在数据库中,然后可以通过 sequencename.nextval().

INSERT 上使用它

序列让您可以控制起始值、increment/decrement 大小、缓存等等。

使用函数last_insert_id()。它将为您提供在调用它之前自动递增的最后一个值。

我是通过使用 PDO lastInsertId() 获取最后插入订单的 ID 来完成的:

$sql = "INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
        VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";

$query = $connection->prepare($sql);    
$query->execute();

$respective_order_id = $connection->lastInsertId();

然后:

INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('{$respective_order_id}', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";

感谢所有试图提供帮助的人!他们让我走上了正确的道路!