MySql外键主键不匹配

时间:2016-05-30 19:08:50

标签: mysql sql

我在将所有外键与主键链接时遇到问题。我有两张桌子:

CREATE TABLE Patients 
        (pid        INT NOT NULL AUTO_INCREMENT,
         name       VARCHAR(25),
         address        VARCHAR(30),
         telephone  VARCHAR(10),
         care_centre_id INT,
CONSTRAINT Patients_PK PRIMARY KEY (pid));

CREATE TABLE Care_centres 
        (cid        INT NOT NULL AUTO_INCREMENT,
         name       VARCHAR(25),
         location       VARCHAR(30),
         nurse_charge_id    INT,
CONSTRAINT Care_centres_PK PRIMARY KEY (cid));

ALTER TABLE Patients ADD FOREIGN KEY (care_centre_id) REFERENCES Care_centres(cid);

cid是Care_centres表的主键,care_cente_id是Patients表的外键。每当我运行查询表(MySql)时,它在外键中显示NULL值。如何索引外键与主键的对应关系,将随机赋值给外键即可。

mysql> SELECT * FROM Patients;
+-----+--------+----------------+------------+----------------+
| pid | name   | address        | telephone  | care_centre_id |
+-----+--------+----------------+------------+----------------+
|   1 | Joe    | 8 Walker Road  | 7800921111 |           NULL |
|   2 | Jose   | 10 Runner Road | 7800922222 |           NULL |
|   3 | Joseph | 12 Jogger Road | 7800923333 |           NULL |
+-----+--------+----------------+------------+----------------+

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

当您在Patients表中插入行时,您需要指定care_centre_id列以创建该患者与指定护理中心之间的关联。否则,数据库无法知道哪个患者属于哪个护理中心。

因此,举例来说,假设你有这样的护理中心:

+-----+--------+----------------+------------+
| cid | name   | location       | nurse_charge_id |
+-----+--------+----------------+------------+
|   1 | centre1| someplace      | 1              |
|   2 | centre2| someplace else | 1              |
例如,你可以将乔和何塞分配给护理中心1,将约瑟夫分配到护理中心2

+-----+--------+----------------+------------+----------------+
| pid | name   | address        | telephone  | care_centre_id |
+-----+--------+----------------+------------+----------------+
|   1 | Joe    | 8 Walker Road  | 7800921111 |           1    |
|   2 | Jose   | 10 Runner Road | 7800922222 |           1    |
|   3 | Joseph | 12 Jogger Road | 7800923333 |           2    |

您可以在初次插入患者期间或随后的更新中执行此操作。