我的表中有三个客户ID,让我们说A,B,C.我想创建订单表来管理这些客户的订单。我想在这样的地方创建orderID列,它必须自动增加,并附加了cunstomer Id。 orderID列记录:
A_1 --->A's 1st order,
A_2 --->A's 2nd order,
B_1 --->B's 1st order,
C_1 --->C's 1st order,
A_3 --->A's 3rd order,
C_2 --->C's 2nd order,
C_3 --->C's 3rd order,
B_2 --->B's 2nd order,
A_4 --->A's 4th order,
A_5 --->A's 5th order
答案 0 :(得分:1)
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`customer_id` BIGINT UNSIGNED NOT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `fk_customer_orders` (`customer_id` ASC)
);
这使您可以轻松INSERT
您的订单,而无需考虑生成的标识符。额外的created
行将允许您对它们进行排序并为它们提供您想要的数字。
$result = $mysqli->query("SELECT * FROM `orders` WHERE `customer_id` = 1 ORDER BY `created`");
$orders = array();
while ($row = $result->fetch_assoc()) {
$orders[] = $row;
}
echo count($orders) , PHP_EOL; // 42
foreach ($orders as $delta => $order) {
echo "Your order #" , ($delta + 1) , " with the unique identifier {$order["order_id"]}." , PHP_EOL;
}
只是一个例子。
答案 1 :(得分:-1)
您可以使用不带PHP的存储过程生成自定义自动增量值,如下所述:
http://en.latindevelopers.com/ivancp/2012/custom-auto-increment-values/
您将获得以下密钥:
SELECT * FROM custom_autonums;
+----+------------+------------+
| id | seq_1 | seq_2 |
+----+------------+------------+
| 4 | 001-000001 | DBA-000001 |
| 5 | 001-000002 | DBA-000002 |
| 6 | 001-000003 | DBA-000003 |
| 7 | 001-000676 | DBA-000004 |
| 8 | 001-000677 | DBA-000005 |
| 9 | 001-000678 | DBA-000006 |
您可以轻松修改以生成自己的自定义自动数字。