mysql关联表(references)的条件:
1。两个表必须是 InnoDB表类型
2。使用在外键关系的域必须为索引型(Index)
3。使用外键关系的域必须与数据类型相似
以下是父表和子表的例子:
创建表时同时创建关联
create table `parent`(
`id` int(11) not null primary key,
`name` varchar(255) not null
) type = innodb;
create table `child`(
`id` int(11),
`parent_id` int(11),
index `parend_ind` (`parent_id`),
foreign key(`parent_id`) references parent(`id`)
on delete cascade
)type=inndob;
建立表之后建立的关联:
(一定要先创建需要的索引)
ALTER TABLE yourtablename
ADD [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
REFERENCES tbl_name (index_col_name, ...)
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
CONSTRAINT symbol 如果被给出,它在数据库必须是唯一的,如果没有给出则自动创建,
CASCADE:从父表删除或更新且自动删除或更新子表中匹配的行
SET NULL:从父表删除或更新行,并设置子表中外键列为NULL;
NO ACTION:意味不采取动作,就是如果有一个相关的外键值在被参考的表里,删除或更新主要键值的企图不被允许进行,InnoDB拒绝对父表的删除或更新操作
RESTRICT:拒绝对父表的删除或更新操作。
SET DEFAULT: 这个动作被解析程序识别,但InnoDB拒绝包含ON DELETE SET DEFAULT或ON UPDATE SET DEFAULT子句的表定义。
大概用法:
mysqli->autocommit(); //关闭事务自动提交
编写别的代码;
mysqli->commit(); // 提交事务让里面的代码执行
mysqli_rollback(); //不执行里面的代码==>事务回滚
1。两个表必须是 InnoDB表类型
2。使用在外键关系的域必须为索引型(Index)
3。使用外键关系的域必须与数据类型相似
以下是父表和子表的例子:
创建表时同时创建关联
create table `parent`(
`id` int(11) not null primary key,
`name` varchar(255) not null
) type = innodb;
create table `child`(
`id` int(11),
`parent_id` int(11),
index `parend_ind` (`parent_id`),
foreign key(`parent_id`) references parent(`id`)
on delete cascade
)type=inndob;
建立表之后建立的关联:
(一定要先创建需要的索引)
ALTER TABLE yourtablename
ADD [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
REFERENCES tbl_name (index_col_name, ...)
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}]
CONSTRAINT symbol 如果被给出,它在数据库必须是唯一的,如果没有给出则自动创建,
CASCADE:从父表删除或更新且自动删除或更新子表中匹配的行
SET NULL:从父表删除或更新行,并设置子表中外键列为NULL;
NO ACTION:意味不采取动作,就是如果有一个相关的外键值在被参考的表里,删除或更新主要键值的企图不被允许进行,InnoDB拒绝对父表的删除或更新操作
RESTRICT:拒绝对父表的删除或更新操作。
SET DEFAULT: 这个动作被解析程序识别,但InnoDB拒绝包含ON DELETE SET DEFAULT或ON UPDATE SET DEFAULT子句的表定义。
大概用法:
mysqli->autocommit(); //关闭事务自动提交
编写别的代码;
mysqli->commit(); // 提交事务让里面的代码执行
mysqli_rollback(); //不执行里面的代码==>事务回滚