简体   繁体   English

外键约束Mysql

[英]Foreign Key Constraint Mysql

I'm trying to create a relationship between a blog and an image, where a blog can have at most one image (think like avatar), but it can also have none. 我正在尝试在博客和图像之间建立一种关系,其中博客最多可以有一个图像(像头像一样),但也可以没有图像。 Therefore, I put the foreign key on the blogs table. 因此,我将外键放在blogs表上。 I was trying to create a constraint on the images table where if the blog gets deleted, its associated image also gets deleted from the database. 我试图在images表上创建一个约束,如果删除了博客,则它的关联映像也会从数据库中删除。 However, I'm not sure how to create the constraint when the foreign key is not in the table that should be cascading. 但是,当外键不在应该级联的表中时,我不确定如何创建约束。 Here's my tables, minus those fields that aren't relevant: 这是我的表格,减去了不相关的字段:

CREATE TABLE `blogs` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `image_id` int(10) unsigned default NULL,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=921 DEFAULT CHARSET=utf8;

CREATE TABLE `images` (
  `id` int(10) unsigned NOT NULL auto_increment,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=251021 DEFAULT CHARSET=utf8 

Any help? 有什么帮助吗?

The only reason to have the images in a separate table would be if the same image could be shared by multiple blogs. 将图像放在单独的表中的唯一原因是同一图像可以被多个博客共享。 In that case you would not want to delete on cascade anyway. 在这种情况下,您无论如何都不想删除级联。 You would need special logic to determine if there were no blogs left that referenced that image to delete it -- something that you could not do through DDL. 您将需要特殊的逻辑来确定是否没有博客可以引用该图像来删除它-这是您无法通过DDL完成的。

Instead, simply make the image values nullable columns on the blogs table. 相反,只需在blogs表上使图像值可为空列即可。

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

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