如果相等则插入

时间:2019-04-11 03:40:15

标签: mysql sql

我的桌子像:

  • 级别

    id:主键

    order:interger

  • 计划

    id:主键

    级别:FOREIGN KEY(级别)

    限制:interger

  • 请求: id:主键

    plan_id:外键(计划)

有请求时,将数据保存到请求表中,此后,我计算所有请求并与表计划中的限制进行比较。如果相等,则将数据插入表级,级别为level + 1的level_id = level_id,否则不执行任何操作。我使用多个单个查询来实现它,但是现在我想在单个查询中对其进行优化。这可能吗?预先感谢

第一:

INSERT INTO request(plan_id) SELECT id FROM PLAN WHERE ...

下一个:

  A =    SELECT COUNT(request.id) FROM request
     WHERE request.plan_id = ...


  B =  SELECT limit FROM plan
     WHERE  ...

如果A = B(我使用php进行比较)

INSERT INTO plan (level_id, order) SELECT id, order FROM level WHERE ..

其他 注意要做

2 个答案:

答案 0 :(得分:1)

我不太了解您正在做的逻辑,但是要回答您的问题,您可以将当前作为A和B查询的内容移到插入内容中的子查询中。像这样:

INSERT INTO plan (level_id, order) 
SELECT id, order 
FROM level 
WHERE {existing where logic here}
AND (
       SELECT COUNT(request.id) FROM request
       WHERE request.plan_id = ...
    ) = (
       SELECT limit FROM plan
       WHERE  ...
    )

如果子查询彼此不相等,则插入操作将不会执行任何操作。

答案 1 :(得分:1)

我认为最好通过编写触发器来监视UPDATE,这样可以更好地处理UPDATE:

CREATE TRIGGER level_trig AFTER INSERT ON request FOR EACH ROW

#new here represents the newly inserted row in request

@A := (SELECT COUNT(request.id) FROM request WHERE request.plan_id = new.plan_id)
@B :=  (SELECT limit FROM plan WHERE plan.id = new.plan_id)

if @A = @B then

#whatever your insert query was. I'm not very clear about that. 

INSERT INTO plan (level_id, order) SELECT id, order FROM level WHERE ..

end if;