Php 级联删除sql
我在一个小网站上工作,涉及数据库的使用,我使用这两个表给用户,在第一个表中我添加用户和他的信息,在第二个表中我只添加Php 级联删除sql,php,mysql,sql,database,html,Php,Mysql,Sql,Database,Html,我在一个小网站上工作,涉及数据库的使用,我使用这两个表给用户,在第一个表中我添加用户和他的信息,在第二个表中我只添加用户id课程id 我的问题是如何在删除时添加级联,在哪个表中 CREATE TABLE IF NOT EXISTS `students` ( `studentid` int(11) NOT NULL AUTO_INCREMENT, `fname` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `lname` varchar
用户id
课程id
我的问题是如何在删除时添加级联
,在哪个表中
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 ;
您需要创建一个
外键
引用学生
表studentid
,使用下面的删除级联
选项
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
)
CREATE TABLE IF note EXISTS`idtables`(
`id`int(11)非空自动增量,
`courseid`varchar(255)校对utf8\u unicode\u ci不为空,
`studentid`char(64)校对utf8\u unicode\u ci不为空,
主键(`id`),
约束FK1外键(studentid)引用学生(studentid)您需要在外键
约束中定义此行为,如:
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 ;
fk_students_id的意思是什么?@CarlosPerez,这是约束名称。@Sammitch非常感谢您的帮助:))如果我使用studentid或courseid来执行级联删除,这是一样的?@CarlosPerez,不,您不能引用courseid
,因为它在学生表中没有定义为主键。@Sammitch,您可以尝试,它也可以很好地工作。@Rahul哦,我明白了,所以要在级联上执行删除操作,我必须使用primary@CarlosPerez,没错,我的意思是,如果您正在创建FK约束,它应该指向另一个表中的PK。此外,在学生表中,studentid的类型是int(11),那么为什么在idtables中将studentid声明为char(64)。。也将其声明为int(11)。