我有一个用户投诉表,其中两列指定每个投诉行的 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 语句来完成,但我只想使用单个 insert 语句。
我不知道该怎么做,请帮忙。我正在使用 mysql、PDO、php
如果您使用 MySQL 触发器,这并不太难。
触发器可以设置为在表中完成 INSERT 后立即自动执行,它会检查 comaplain_code 是否为空。如果它为空,也将使用complain_id 的下一个自动增量值作为comaplain_code:
通过运行以下命令创建触发器:
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 ;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句