【问题标题】:create a trigger a student is not taking repeat course(mysql)创建一个学生不参加重复课程的触发器(mysql)
【发布时间】:2017-12-05 13:48:02
【问题描述】:

我在用mysql做一个学生选课系统,注册系统有一个数据表,表字段是sno(学生id)和cno(课程id),如何在mysql中创建触发器防止学生选择重复课程?

【问题讨论】:

  • 为什么要在这里寻找触发器?两列上的唯一索引应该可以完成工作
  • 抱歉,这是为了我的家庭作业
  • 唯一键也是一种解决方案
  • 再说一遍:为什么必须在这里使用触发器?一个触发器应该用于一个接一个地执行一些动作——在这里,你想收到一个无效数据的错误,这可以通过唯一索引完美解决
  • 谢谢!我会试试这个方法。

标签: mysql triggers


【解决方案1】:

student idcourse id一起为主键设置注册表。如果你能避免触发,这样会更容易。

如果你想触发:

delimiter //
drop trigger if exists limitCoursesTrigger //
create trigger limitCoursesTrigger before insert on register_table
for each row
begin
    declare msg varchar(128);
    if exists(select * from register_table where studentid=new.studentid and courseid=new.courseid)
    then
        set msg = concat('Error: The student has already registered for this course !');
        signal sqlstate '45000' set message_text = msg;
    end if;
end //

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2021-11-18
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2011-02-03
    • 2016-09-19
    相关资源
    最近更新 更多