如何在table中加入foreign key?

onceuponatime 2008-07-21 06:23:50
比如我有一个table1,一个table2,怎样在table1中把table2的primary key 加成一列foreign key?表达式是什么?
...全文
239 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
tzheng517 2008-07-31
  • 打赏
  • 举报
回复

下面是个示例,两张表,看了就知道怎么用Sql语句写了
表一: 用户表
CREATE TABLE users (
uid int(11) NOT NULL auto_increment,
uname varchar(20) NOT NULL,
usex char(2) NOT NULL,
PRIMARY KEY (uid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

表二:订单表
TABLE orders (
oid int(11) NOT NULL auto_increment,
odate timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
cid int(11) default NULL,
PRIMARY KEY (oid),
KEY cid (cid),
CONSTRAINT orders_fk FOREIGN KEY (cid) REFERENCES customer (cid)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
jrg9522 2008-07-22
  • 打赏
  • 举报
回复
ydage正解。
或用工具很容易就加上或取消外键约束了。
ydage 2008-07-21
  • 打赏
  • 举报
回复
#前提是table1,table2的表引擎都是innodb
create table table2(a2 int primary key,
......
) engine = innodb

create table table1(
a1 int primary key,
a2 int,
......
foreign key (a2) references table2(a2)
) engine = innodb

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧