Mysql, 如何读取同一插入行的其他字段的自增值?

Mysql, How to read auto increment value in other fields of the same inserting row?

您好,我需要在交易的评论字段中输入交易 ID

mysql_query("INSERT INTO `transactiontb` (`tid`, `amount`, `comment`) VALUES (NULL,'$amount', CONCAT('Transaction # ',`tid`)')");

我该怎么做?

使用LAST_INSERT_ID()函数。

LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value representing the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement to affect such a column.

来源:MySQL Documentation

示例:

"INSERT INTO transactiontb(tid, amount, comment) VALUES (NULL,'" . $amount . "', CONCAT_WS('#','Transaction',LAST_INSERT_ID(id+1)))"

刚刚看到您也忘记了为您设置分隔符 CONCAT_WS 函数,所以我在示例查询中修复了它。

  1. 摆脱 mysql_* 函数。看看 MySQLi 或 PDO。
  2. 不要存储 tid 两次。当你 select 它而不是那样存储时,为什么不连接呢?这不是最好的方法。

作为参考,请尝试 LAST_INSERT_ID()+1):

INSERT INTO `transactiontb` (`tid`, `amount`, `comment`)
VALUES (NULL, '$amount', CONCAT_WS('Transaction # ', LAST_INSERT_ID()+1))

LAST_INSERT_ID() 将给出前一个 INSERT 的 ID,而不是当前 INSERT 的 ID,因此您必须加 1。

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.