MySQL触发增量部分

时间:2015-09-18 12:27:50

标签: mysql

我正在使用MySQL数据库,并希望在表'jobs'上的任何插入之前创建一个触发器

我的架构如下:

+-------------+     +--------------+
|    jobs     |     |   machines   |
+-------------+     +--------------+
| job_id      |  ___| machine_id   |
| job_machine |_|   | machine_name |
| job_name    |     +--------------+
| job_start   |
+-------------+     

jobs.job_machine和machines.machine_id

之间有一个外键

job_start是一个日期时间,将用于填充job_name。但它会像这样形成

select DATE_FORMAT(job_start, "%y%m%d") from jobs where NEW.job_id;

我希望job_name成为job_start + job_machine + increment的串联。我会解释一下。

例如,如果插入的作业是

+--------+-------------+-----------------------+----------+
| job_id | job_machine |       job_start       | job_name |
+--------+-------------+-----------------------+----------+
|      1 |           3 | '2015-09-18 14:20:00' |          |
+--------+-------------+-----------------------+----------+

job_name将是:15091831

但如果同一天在同一台机器上创建类似的作业,则为15091832

我有

CREATE DEFINER = CURRENT_USER TRIGGER `myTable`.`jobs_BEFORE_INSERT` BEFORE INSERT ON `jobs` FOR EACH ROW
BEGIN
    select concat((select DATE_FORMAT(job_start, "%y%m%d") from jobs where job_id=NEW.job_id) , (select job_machine from jobs where job_id = NEW.job_id));
END

但我对增量部分不太确定。最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

您的触发逻辑不完整。例如,您没有在new中设置任何值,因此触发器不执行任何操作。

我认为以下是您想要的:

CREATE DEFINER = CURRENT_USER TRIGGER `myTable`.`jobs_BEFORE_INSERT`
     BEFORE INSERT ON `jobs` FOR EACH ROW
BEGIN
    select new.job_id := concat(DATE_FORMAT(new.job_start, '%y%m%d'), new.job_machine,
                                RIGHT(MAX(job_name), 1) + 1)
    from jobs j
    where j.job_start >= date(new.job_start) and
          j.job_start < date(new.job_start) + interval 1 day and
          j.job_machine = new.job_machine
END

答案 1 :(得分:0)

首先确定当前的增量值,然后将其用于id和name:

CREATE DEFINER = CURRENT_USER TRIGGER `myTable`.`jobs_BEFORE_INSERT`
 BEFORE INSERT ON `jobs` FOR EACH ROW
BEGIN
DECLARE next_id integer;
 -- select the current highest id and increment it
SET @next_id := (select max(job_id)+1
    from jobs 
    where DATE_FORMAT(job_start, '%y%m%d') = DATE_FORMAT(NEW.job_start, '%y%m%d') 
        and job_machine = NEW.job_machine);
-- if it is the first job for this machine this day then make it nr 1
IF ISNULL(@next_id) THEN
    SET @next_id := 1;
END IF;
-- then set your new row accordingly
SET NEW.job_id = @next_id;
SET NEW.job_name = concat(DATE_FORMAT(NEW.job_start, '%y%m%d'), job_machine, @next_id);
END