表创建后的外键

时间:2014-04-15 05:15:07

标签: mysql sql

我已经在MySQL中创建了一个表!并尝试了一些查询来改变表并向表中添加外键! 但它们都不起作用? 没有任何错误消息,但没有任何事情发生......

我需要确切的查询才有效! :(

详细说明:

  1. 表1:用户列: id
  2. 表2: Pokemon_ref 栏目: pkmn_id
  3. 如果在表1中完成插入,那么它也应该在表2中添加!

2 个答案:

答案 0 :(得分:1)

    category INT NOT NULL, id INT NOT NULL,
    price DECIMAL,
    PRIMARY KEY(category, id)
)   ENGINE=INNODB;

CREATE TABLE customer (
    id INT NOT NULL,
    PRIMARY KEY (id)
)   ENGINE=INNODB;

CREATE TABLE product_order (
    no INT NOT NULL AUTO_INCREMENT,
    product_category INT NOT NULL,
    product_id INT NOT NULL,
    customer_id INT NOT NULL,

    PRIMARY KEY(no),
    INDEX (product_category, product_id),
    INDEX (customer_id),

    FOREIGN KEY (product_category, product_id)
      REFERENCES product(category, id)
      ON UPDATE CASCADE ON DELETE RESTRICT,

    FOREIGN KEY (customer_id)
      REFERENCES customer(id)
) 

答案 1 :(得分:1)

样品:

ALTER TABLE tablename
ADD CONSTRAINT FK_Name_ID FOREIGN KEY (fk_ID)
    REFERENCES (R_id);

<强> https://dev.mysql.com/doc/refman/5.1/en/create-table-foreign-keys.html

<强> http://www.w3schools.com/sql/sql_foreignkey.asp

<强> Alter table to give foreign key constraint