Parsing: A method for establishing a foreign key in MySQL
Example:
1. Main Table
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. Table Cotton
Relationship is 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;
(Note: Be sure to remember varchar (11), or you may have an error that you can see from the existing Table export SQL).
The result of this SQL statement being exported with Sql-front is:
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`);