比如我有一个table1,一个table2,怎样在table1中把table2的primary key 加成一列foreign key?表达式是什么?

解决方案 »

  1.   

    #前提是table1,table2的表引擎都是innodb
    create table table2(a2 int primary key,
    ......
    ) engine = innodbcreate table table1(
    a1 int primary key,
    a2 int,
    ......
    foreign key (a2) references table2(a2) 
    ) engine = innodb
      

  2.   

    ydage正解。
    或用工具很容易就加上或取消外键约束了。
      

  3.   


    下面是个示例,两张表,看了就知道怎么用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;