【问题标题】:SQL Trigger on Insert into one table, copy into another multiple times插入一个表时的 SQL 触发器,多次复制到另一个表中
【发布时间】:2012-02-29 08:16:41
【问题描述】:

我在我的数据库中设置了 2 个表 - Fitness_report 和 result。

fitness_report 包含以下列(按顺序):

report_id, test_period, test_date, student_id

结果有以下列(按顺序):

test_id, student_id, report_id, score

我需要做的是当在表 Fitness_report 上创建新行时, 结果表中的条目如下所示,其中 student_id 和 report_id 是从 Fitness_report 上的新行中复制的:

1, student_id, report_id, null
2, student_id, report_id, null
3, student_id, report_id, null
4, student_id, report_id, null
5, student_id, report_id, null
6, student_id, report_id, null

您能否建议最好的方法来执行此操作。

干杯

【问题讨论】:

    标签: mysql sql triggers


    【解决方案1】:

    您可以在INSERT 事件上创建触发器。检查this

    CREATE TRIGGER myTrigger AFTER INSERT ON fitness_report 
      FOR EACH ROW BEGIN
        INSERT INTO results SET student_id = NEW.student_id, report_id=NEW.report_id;  
      END;
    

    【讨论】:

    • 这会将student_id和report_id插入到结果表中,但是我如何插入静态数据呢? (test_id 和分数)?
    • 这项工作是否有效:在每行插入健身报告后创建触发器新报告开始插入结果(1,NEW.student_id,NEW.report_id,null);插入结果(2,NEW.student_id,NEW.report_id,null);插入结果(3,NEW.student_id,NEW.report_id,null);插入结果(4,NEW.student_id,NEW.report_id,null);插入结果(5,NEW.student_id,NEW.report_id,null);结束;
    • 试试INSERT INTO results SET student_id = NEW.student_id, report_id=NEW.report_id, score=null;。可以重复INSERT语句插入多条记录。
    • 我收到以下错误:#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在第 3 行的 '' 附近使用的正确语法
    • 让我知道它是否有效。我会相应地更新答案。虽然 AFTER INSERT 是首选。您可以检查文档中的语法。
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2014-02-06
    • 1970-01-01
    相关资源
    最近更新 更多