听起来 HOME 需要自己的单独标识符。ID 是什么并不重要……只要它是唯一的。
考虑以下:
mysql> CREATE TABLE HOME (ID INTEGER NOT NULL auto_increment, ROOM_NUM INTEGER, BUILD_CODE VARCHAR(1), PRIMARY KEY(ID));
Query OK, 0 rows affected (0.14 sec)
mysql> CREATE TABLE PERSON(ID INTEGER NOT NULL auto_increment, NAME VARCHAR(255), HOME_ID INTEGER, PRIMARY KEY(ID), FOREIGN KEY(HOME_ID) REFERENCES HOME(ID));
Query OK, 0 rows affected (0.14 sec)
mysql> INSERT INTO HOME (ROOM_NUM, BUILD_CODE) VALUES (302, "A"), (205, "B");
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM HOME;
+----+----------+------------+
| ID | ROOM_NUM | BUILD_CODE |
+----+----------+------------+
| 1 | 302 | A |
| 2 | 205 | B |
+----+----------+------------+
2 rows in set (0.00 sec)
mysql> INSERT INTO PERSON (NAME, HOME_ID) VALUES ("someone", 1);
Query OK, 1 row affected (0.05 sec)
mysql> SELECT * FROM PERSON;
+----+---------+---------+
| ID | NAME | HOME_ID |
+----+---------+---------+
| 1 | someone | 1 |
+----+---------+---------+
1 row in set (0.00 sec)
mysql> SELECT PERSON.NAME, HOME.BUILD_CODE, HOME.ROOM_NUM FROM HOME JOIN PERSON ON PERSON.HOME_ID = HOME.ID;
+---------+------------+----------+
| NAME | BUILD_CODE | ROOM_NUM |
+---------+------------+----------+
| someone | A | 302 |
+---------+------------+----------+
1 row in set (0.00 sec)
你看,它HOME
的ID
值对其余数据的影响并不大……你只是将该字段用作将两者结合在一起的工具。
当然,您也可以轻松地INSERT
将BUILD_CODE
andROOM_NUM
字段连接到ID
字段中......这也很好。但请记住,(a)字符串查找比整数查找使用更多的资源,并且(b)这只是您的应用程序需要维护的另一件事(例如:如果您从将房间号计算为 A302 开始会发生什么,但是在看到更大的房间号之后,您决定选择 A00302?您必须遍历整个表——以及它的所有关联——并更新ID
. 这不是非常理想)。