0

如何使 message_id 成为外键,以便评论和消息之间是一对多的?(一条消息可以有很多评论。)

mysql> use nntp;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------+
| Tables_in_nntp |
+----------------+
| comments       |
| messages       |
+----------------+
2 rows in set (0.00 sec)

mysql> describe comments;
+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| id         | int(11) | NO   | PRI | NULL    |       |
| message_id | int(11) | NO   |     | NULL    |       |
| comment    | text    | NO   |     | NULL    |       |
| stamp      | date    | NO   |     | NULL    |       |
+------------+---------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> describe messages;
+-----------+---------+------+-----+---------+-------+
| Field     | Type    | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| id        | int(11) | NO   | PRI | NULL    |       |
| newsgroup | text    | NO   |     | NULL    |       |
| subject   | text    | NO   |     | NULL    |       |
| content   | text    | NO   |     | NULL    |       |
| number    | text    | NO   |     | NULL    |       |
+-----------+---------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> quit
Bye
thufir@dur:~/NetBeansProjects/USENET$ 

我正在使用 MySql 查询浏览器并查看:

在此处输入图像描述

虽然我可以从查询浏览器或命令行输入 SQL,但我对它不是很熟悉。如果可能的话,我更愿意为此使用 GUI 查询浏览器。

4

1 回答 1

2

应该做的伎俩:

ALTER TABLE comments ADD FOREIGN KEY (message_id) REFERENCES messages(id);

从阅读MySQL 文档中可以看出。

于 2012-07-26T13:21:47.453 回答