简体   繁体   中英

MySql query browser: alter table for foreign key

how do I make message_id a foreign key so that it's one-to-many between comments and messages? (One message can have many comments.)

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$ 

I'm using the MySql query browser and see:

在此输入图像描述

While I can enter SQL either from the query browser or command line, I'm not very familiar with it. I would prefer to use the GUI query browser, if possible, for this.

Should do the trick:

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

As one could tell from reading the MySQL documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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