2

Im working on a small website that involves the use of databases, I'm using this two tables to users, in the first table i add the users and his information, and in the second one I add only the user id the course id.

My question is how can I add the cascade on delete, in which table?

CREATE TABLE IF NOT EXISTS `students` (
  `studentid` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `lname` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `studentcode` varchar(16) COLLATE utf8_unicode_ci NOT NULL,
  `courseid` int(11) NOT NULL,
  PRIMARY KEY (`studentid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=27 ;

CREATE TABLE IF NOT EXISTS `idtables` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `courseid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `studentid` char(64) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=43 ;
Carlos Perez
  • 443
  • 3
  • 13

2 Answers2

1

You need to create a FORIEGN KEY referencing to students table studentid with ON DELETE CASCADE option like below

CREATE TABLE IF NOT EXISTS `idtables` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `courseid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `studentid` char(64) COLLATE utf8_unicode_ci NOT NULL,
   PRIMARY KEY (`id`),
   CONSTRAINT FK1 FORIEGN KEY(studentid) REFERENCES students(studentid) <-- Here
   ON DELETE CASCADE <-- HERE
) 
Rahul
  • 73,987
  • 13
  • 62
  • 116
1

You need to define this behaviour in a FOREIGN KEY constraint like:

CREATE TABLE IF NOT EXISTS `idtables` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `courseid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `studentid` char(64) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY fk_students_id (studentid)
    REFERENCES students (id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=43 ;
Sammitch
  • 27,459
  • 7
  • 46
  • 75