简体   繁体   English

MySQL关联数据库中的表

[英]MySQL relating tables in the database

In the video tutoria/book I am using to learn about PHP and SQL, the author is explaining the concept of the foreign key to make database tables relate to each other. 在我用来学习PHP和SQL的视频Tutoria /书中,作者解释了使数据库表相互关联的外键的概念。 As you will see in the image below, we are currently making a table called "comments." 如您在下图中所看到的,我们当前正在创建一个名为“ comments”的表。 Within this SQL, there is a line photograph_id INT( 11 ) NOT NULL, called the "foreign key," which the author says relates the "comments" table to the already existing "photographs" table. 在此SQL中,有一行photograph_id INT( 11 ) NOT NULL,称为“外键”,作者说该行将“评论”表与现有的“照片”表相关。

My question is, since the table is called "photographs" (plural with an s), but the sql foreign key is "photograph_id", how does SQL connect the two? 我的问题是,由于表称为“ photographs”(复数为s),但是sql外键为“ photograph_id”,SQL如何将两者连接起来? What exactly is it about "photograph_id" that allows MySQL to relate it to "photographs" table. “ photograph_id”的确切含义是什么,它允许MySQL将其与“ photographs”表关联。

+-----------------------------+
| Tables_in_C263430_quoralist |
+-----------------------------+
| photographs                 |
| users                       |
+-----------------------------+
2 rows in set (0.21 sec)

mysql> CREATE TABLE comments (
    -> id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> photograph_id INT( 11 ) NOT NULL,
    -> created DATETIME NOT NULL,
    -> author VARCHAR( 255 ) NOT NULL,
    -> body TEXT NOT NULL
    -> );

MySQL does not "connect" the two tables automatically, you have to do that yourself: MySQL不会自动“连接”这两个表,您必须自己做:

CREATE TABLE comments (
id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY,
photograph_id INT( 11 ) NOT NULL,
created DATETIME NOT NULL,
author VARCHAR( 255 ) NOT NULL,
body TEXT NOT NULL,
FOREIGN KEY (`photograph_id`) REFERENCES `photographs` (`id`) ON DELETE CASCADE
);

This will tell MySQL that your table comments has a foreign key. 这将告诉MySQL您的表comments具有外键。 You didn't specify a name for the key, so mysql will choose a name itself. 您没有为键指定名称,因此mysql将自行选择名称。 They key is on the column photograph_id of that table. 它们的键在该表的“ photograph_id ”列上。 The key refers to the table photographs , its column id . 键是指表格中的photographs ,其列id

Maybe the author meant that you use the column to "emulate" a foreign key, meaning you use that key to join to the primary key of photographs, without really adding the Foreign Key Constraint. 也许作者的意思是您使用该列来“模拟”外键,这意味着您可以使用该键连接到照片的主键,而无需真正添加外键约束。 So you, the database administrator, know that the field is used for a relation, but the database itself does not (and hence will not check the integrity of the field: you could add a comment to a photograph that does not exist). 因此,数据库管理员您知道该字段用于关联,但是数据库本身不使用该字段(因此不会检查该字段的完整性:您可以为不存在的照片添加注释)。

The photographs table may look like this: 照片表可能如下所示:

photograph_id        image_path
========================================
34343                /images/img_343.jpg
34344                /images/img_344.jpg
34345                /images/img_345.jpg
34346                /images/img_346.jpg
34347                /images/img_347.jpg

Which is a set of photograph file names stored in database. 这是存储在数据库中的一组照片文件名。 Note that some people also resort to storing the photograph itself in database in a BLOB format. 请注意,有些人还诉诸于将照片本身以BLOB格式存储在数据库中。

When a comment record is created, the SQL is specifying which of the above photograph records to use for the photograph. 创建注释记录后,SQL将指定上面的哪些照片记录用于该照片。

The actual name of the foreign key field doesn't matter much; 外键字段的实际名称无关紧要; it's mostly for documentation. 它主要用于文档。 The usual naming convention for tables is that they are the plural of whatever each row represents, while the column name is the singular. 对于表,通常的命名约定是它们是每行代表的复数形式,而列名是单数形式。

The tables are tied together by specifying a foreign key constraint in the dependent table (comments, in your example). 通过在从属表(在您的示例中为注释)中指定外键约束,将表绑定在一起。 Be aware that the storage engine used for each table affects whether the foreign key constraint is enforced by the system. 请注意,用于每个表的存储引擎会影响外键约束是否由系统强制执行。 The default MyISAM storage engine does not enforce constraints; 默认的MyISAM存储引擎强制限制; the InnoDB storage engine does. InnoDB存储引擎可以。

@Michael: As @Konerak notes, you have to specify it yourself. @Michael:正如@Konerak所说,您必须自己指定。 MySQL creates tables using the MyISAM engine by default for which the FOREIGN KEY clause is ignored. 默认情况下,MySQL使用MyISAM引擎创建表,对于该表, FOREIGN KEY子句将被忽略。 Both your tables must be InnoDB . 您的两个表都必须是InnoDB I suggest you also have a look at this introduction to foreign keys and referential integrity in MySQL -- http://www.techrepublic.com/article/an-introduction-to-foreign-keys-and-referential-integrity-in-mysql/6035435 我建议您也对MySQL中的外键和引用完整性进行一下介绍-http: //www.techrepublic.com/article/an-introduction-to-foreign-keys-and-referential-integrity-in- mysql / 6035435

You have to tell it by defining a foreign key. 您必须通过定义外键来告诉它。 The syntax goes like this: 语法如下:

ALTER TABLE comments ADD CONSTRAINT fk_photgraph_id FOREIGN KEY (photograph_id) REFERENCES photographs (id)

(You can do the same in one go inside the CREATE TABLE statement, but I prefer the above, because this way you can first create all your tables, and then add the foreign keys, without worrying about the correct order). (您可以在CREATE TABLE语句中一次执行相同的操作,但是我更喜欢上面的方法,因为这样您可以先创建所有表,然后添加外键,而不必担心正确的顺序)。

This will tell MySQL that the photograph_id column in the comments table links to the id column in the photographs table. 这将告诉MySQL, comments表中的photograph_id列链接到photographs表中的id列。 From then on, MySQL will check for you that any photograph_id is associated with a valid photographs.id ; 从那时起,MySQL将为您检查是否有任何photograph_id与有效的photographs.id相关联; by adding ON UPDATE and ON DELETE statements, you can control how exactly it does that - for example, if you specify ON DELETE CASCADE , then deleting a photograph will also delete all comments that reference it; 通过添加ON UPDATEON DELETE语句,您可以控制其执行的精确度-例如,如果指定ON DELETE CASCADE ,则删除照片还将删除所有引用该照片的注释; ON DELETE SET NULL will set the comments' photograph_id to NULL instead; ON DELETE SET NULL会将注释的photograph_id设置为NULL; ON DELETE NO ACTION and ON DELETE RESTRICT will refuse to delete the photograph until all comments have been removed or assigned to a different photograph. ON DELETE NO ACTION所有评论或将其分配给另一张照片之前,“不删除ON DELETE NO ACTION和“ ON DELETE RESTRICT将拒绝删除照片。 Cascading deletes are very powerful, so be careful when using them. 级联删除功能非常强大,因此在使用它们时要小心。 You might delete more things than you intend to, and databases don't have an 'undo' button. 您可能删除的东西超出了您的预期,并且数据库没有“撤消”按钮。

An important point to remember is that foreign keys in MySQL only work with the InnoDB storage engine; 需要记住的重要一点是,MySQL中的外键仅适用于InnoDB存储引擎。 MyISAM does not support foreign keys. MyISAM不支持外键。 If you specify a foreign key on a MyISAM table, MySQL will happily parse it and then ignore it without raising any errors. 如果在MyISAM表上指定外键,MySQL将很乐意对其进行解析,然后忽略它而不会引发任何错误。

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

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