如何在两列中使用自动增量值

How Use Auto Increment value in two columns

我有一个用户抱怨 table 其中两列指定每个抱怨行的 id

`complaint_id` MEDIUMINT UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`complaint_code` VARCHAR(20) NOT NULL ,

我想如果用户提供 complain_code 那么它将被正常插入并且 complaint_id 有它的 AUTO_INCREMENTED 值, 但是如果用户跳过填写 complain_code 字段,那么它也由 complain_id 的 AUTO_INCREMENTED 值填充,与 complaint_id.

相同

我可以使用 Insert then Update 语句来做到这一点,但我只想使用 单个插入语句。

我不知道该怎么做,请帮忙。我正在使用 mysql、PDO、php

如果您使用 MySQL 触发器,这并不难。

触发器可以设置为在您的 table 中完成插入后立即自动执行,并且它会检查 comaplain_code 是否为空。如果它是空白的,将对 comaplain_code 使用下一个 complain_id 的自动增量值:

通过 运行 创建触发器:

DELIMITER $$
CREATE TRIGGER update_complain_code
BEFORE INSERT ON `user_complaints` FOR EACH ROW
begin
    DECLARE next_id INT;
    SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='user_complaints');

    IF NEW.complaint_code is NULL OR NEW.complaint_code = ''
    THEN
        SET NEW.complaint_code=next_id;
    END IF;
END;
$$
DELIMITER ;