在庫和書籍之間使用關係模型並使用連接查詢它。只要您的主鍵和索引設置爲library_id
,這個速度相當快。
table: libraries
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | YES | PRI | NULL | |
| name | varchar(100) | NO | | NULL | |
+-------+--------------+------+-----+---------+-------+
+------+------+
| id | name |
+------+------+
| 1 | Foo |
| 2 | Bar |
+------+------+
table: books
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| library_id | int(11) | NO | MUL | NULL | |
| author | varchar(100) | NO | | NULL | |
| name | varchar(100) | NO | | NULL | |
+------------+--------------+------+-----+---------+-------+
+----+------------+--------+------+
| id | library_id | author | name |
+----+------------+--------+------+
| 1 | 1 | Jon | Baz |
| 2 | 1 | Bill | Baz |
| 3 | 2 | Mary | Abc |
+----+------------+--------+------+
這樣就可以很方便的查詢。爲了找到符合的「富」的名稱庫中的所有書籍,你會使用這樣的查詢:
mysql> SELECT books.* FROM books
-> JOIN libraries ON libraries.id = books.library_id
-> AND libraries.name = 'Foo';
+----+------------+--------+------+
| id | library_id | author | name |
+----+------------+--------+------+
| 1 | 1 | Jon | Baz |
| 2 | 1 | Bill | Baz |
+----+------------+--------+------+
如果你已經知道庫ID,你甚至都不需要一個連接:
mysql> SELECT * FROM books
-> WHERE library_id = 2;
+----+------------+--------+------+
| id | library_id | author | name |
+----+------------+--------+------+
| 3 | 2 | Mary | Abc |
+----+------------+--------+------+
用外鍵,這是否意味着mysql不必建立一個臨時表,然後對結果集進行排序? E.G與整個書的結果集的加入值把一個臨時表開始實際排序前? – 2011-04-24 16:38:00