简体   繁体   English

如何在MySQL中创建小型关系数据库?

[英]How can I create a small relational database in MySQL?

I need to make a small database in MySQL that has two tables. 我需要在MySQL中建立一个具有两个表的小型数据库。

Clothes and ClotheType 衣服和衣服类型

Clothes has: ID, Name, Color, Brand, Price, ClotheTypeID ClotheType has: ID, Description 衣服具有:ID,名称,颜色,品牌,价格,ClotheTypeID ClotheType具有:ID,描述

In Microsoft SQL it would be: 在Microsoft SQL中,它将是:

create table Clothes(
id int,
primary key(id),
name varchar(200),
color varchar(200),
brand varchar(200),
price varchar(200),
clothetypeid int,
foreign key clothetypeid references ClotheType(id)
)

I need this in MySQL. 我在MySQL中需要这个。

create table Clothes(
    id int,
    primary key(id),
    name varchar(200),
    color varchar(200),
    brand varchar(200),
    price varchar(200),
    clothetypeid int,
    constraint `constr_Clothes_clothetypeid_fk` foreign key `clothetypeid_fk` (`clothetypeid`) references `ClotheType`(`id`)
) ENGINE=INNODB

NB. 注意

  • id must be an indexed column in table ClotheType , and it must have the same type (ie int) id必须是表ClotheType的索引列,并且必须具有相同的类型(即int)
  • ClotheType must also be ENGINE=INNODB . ClotheType也必须为ENGINE=INNODB If you have already created it then you can change it using ALTER TABLE ClotheType ENGINE=INNODB 如果已经创建,则可以使用ALTER TABLE ClotheType ENGINE=INNODB进行ALTER TABLE ClotheType ENGINE=INNODB

To answer the question you posed in your comment on Ólafur's answer: MySQL handles foreign key constraints natively in as much as it parses the relevant data definition language statements, but some of its storage engines do not support them. 为了回答您在Ólafur答案中的评论中提出的问题:MySQL在解析相关数据定义语言语句的同时,会以本机方式处理外键约束,但某些存储引擎不支持它们。 The default storage engine in most MySQL installations is MyISAM, which does not support foreign keys. 大多数MySQL安装中的默认存储引擎是MyISAM,它不支持外键。 InnoDB does support them. InnoDB确实支持它们。

You can use the InnoDB database engine in MySQL (instead of the default MyISAM), it has foreign key constraints. 您可以在MySQL中使用InnoDB数据库引擎(而不是默认的MyISAM),它具有外键约束。

Here is the MySQL documentation entry on the InnoDB Foreign Key Constraints 这是有关InnoDB外键约束的MySQL文档条目

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

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