简体   繁体   English

MySQL中的外键约束

[英]Foreign Key constraints in MySQL

I am a newbie to PHP. 我是PHP的新手。 I have been given the code snippet below as homework: 我得到了下面的代码片段作为作业:

CREATE  TABLE `admin_log`   (
`id`    INT(11) NOT NULL    AUTO_INCREMENT,
`statusdate`    DATETIME    DEFAULT NULL,
`type` INT(11) DEFAULT  NULL
PRIMARY KEY (`id`)  

)   ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin 

Why will it not be possible to set up any foreign key constraints using this table? 为什么无法使用此表设置任何外键约束?

I have done some research on Google and I cant find a reason why foreign key constraints are not possible. 我已经在Google上进行了一些研究,但找不到找不到外键约束的原因。 Please help 请帮忙

You can do that like this : 您可以这样:

CREATE  TABLE `admin_log`   (
`id`    INT(11) NOT NULL    AUTO_INCREMENT,
`statusdate`    DATETIME    DEFAULT NULL,
`type` INT(11) DEFAULT  NULL,

 INDEX (type),
 FOREIGN KEY (type)
    REFERENCES type(id)
    ON UPDATE CASCADE ON DELETE RESTRICT,

PRIMARY KEY (`id`)  
)   ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=latin 

Notice the engine INNODB insetad of MYISAM which doesn't permit foreign key. 注意MYISAM它不允许外键的发动机INNODB insetad。

Or using MySQLAdmin in the "structure" tab, click on the "relationals view" link below the table description. 或在“结构”选项卡中使用MySQLAdmin,单击表描述下方的“关系视图”链接。

Even it has been mentioned on comment before -- just to make it more prominent: MyISAM is not supporting foreign keys. 甚至在以前的评论中也提到过它-只是为了使其更加突出:MyISAM不支持外键。 So you will need to change the engine of your table to eg INNODB if possible. 因此,如果可能,您将需要将表的引擎更改为INNODB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM