开发者

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. As you will see in the image below, we are currently making a table called "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.

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? What exactly is it about "photograph_id" that allows MySQL to relate it to "photographs" table.

+-----------------------------+
| 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,
    -> cre开发者_运维知识库ated 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:

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. You didn't specify a name for the key, so mysql will choose a name itself. They key is on the column photograph_id of that table. The key refers to the table photographs, its column 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.

When a comment record is created, the SQL is specifying which of the above photograph records to use for the photograph.


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; the InnoDB storage engine does.


@Michael: As @Konerak notes, you have to specify it yourself. MySQL creates tables using the MyISAM engine by default for which the FOREIGN KEY clause is ignored. Both your tables must be 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


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).

This will tell MySQL that the photograph_id column in the comments table links to the id column in the photographs table. From then on, MySQL will check for you that any photograph_id is associated with a valid 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 DELETE SET NULL will set the comments' photograph_id to NULL instead; 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. 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; MyISAM does not support foreign keys. If you specify a foreign key on a MyISAM table, MySQL will happily parse it and then ignore it without raising any errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜