在My
SQL数据库中建立外键:
示例:
1.主表
DROP TABLE IF EXISTS `biao`;
CREATE TABLE `biao` (
id` int(11) NOT NULL auto_increment,
title` varchar(11) default NULL,
content` varchar(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
2.表cotton
关系是1:N
。drop table cotton;
create table cotton(
id int primary key,
user varchar(11),
email varchar(11),
url varchar(11),
content varchar(11),
addTime date,
biao_id int,
constraint FK_biao_id foreign key (blog_id) references biao(id)
)ENGINE=InnoDB DEFAULT CHARSET=gb2312;
(注释:一定要记住varchar(11)
,否则可能就会出现错误
,从已有表导出sql才看以出)
。此sql语句用sql-front导出后的结果是:
DROP TABLE IF EXISTS `comment`;
CREATE TABLE `comment` (
`id` int(11) NOT NULL,
`user` varchar(11) default NULL,
`email` varchar(11) default NULL,
`url` varchar(11) default NULL,
`content` varchar(11) default NULL,
`addTime` date default NULL,
`blog_id` int(11) default NULL,
PRIMARY KEY (`id`),
KEY `FK_blog_id` (`blog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
ALTER TABLE `comment`
ADD FOREIGN KEY (`blog_id`) REFERENCES `blog` (`id`);