[英]Database design for select performance
對於性能,當我想過濾具有特定城市特定愛好的用戶時,waht是業余愛好和城市領域的最佳數據庫用戶表設計?
解決方案1 - N1表
用戶表
ID ........ | NAME .. | CITY ..... | 嗜好............................. |
VALUE | 價值| 價值| VALUE1,VALUE2,VALUE3 |
解決方案2 - N1表
用戶表
ID ........ | NAME .. | CITY ..... | HOBBIY1 | HOBBIY2 | HOBBIY3 | HOBBIY4 | HOBBIY5 | HOBBIY6 |
VALUE | 價值| 價值| 價值...... | 價值...... | 價值...... | 價值...... | 價值...... | 價值...... |
解決方案3 - N2表
1 - 用戶表
ID ....... | NAME .. | 城市.... |
價值| 價值| 價值|
2 - HOBBIES TABLE
ID ....... | HOBBY |
價值| 價值|
什么是最好的PHP查詢列出一個有業余愛好的城市的用戶?
怎么樣:
Tables:
---------
user:
user_id, (Primary Key - DB will create index automatically)
username, (Add unique index to prevent duplicate usernames)
created_on
city:
city_id, (Primary Key)
country, (You may want to index some of these location fields, but I would
region, wait until you see the need for them based on your queries)
city,
latitude,
longitude
user_location:
user_id, (If you want a user to only have one location, then create a primary
city_id, key for user_id and city_id. (Composite) If you want to allow multiple
update_on per user then create a non-unique composite index on user_id and city_id
user_hobby:
user_id, (Create a unique composite index on user_id and hobby_id)
hobby_id
hobby:
hobby_id, (Primary Key)
hobby_name (Create a unique index to prevent duplicate hobbies with different keys)
SQL:
---------
SELECT user_id, username, c.country, c.region, c.city
FROM user u
JOIN user_location ul ON (u.user_id = ul.user_id)
JOIN city c ON (ul.city_id = c.city_id)
JOIN user_hobby uh ON (h.user_id = uh.user_id)
JOIN hobby h ON (uh.hobby_id = h.hobby_id)
WHERE h.hobby_name = 'Model Cars';
您可能會發現其中一些對您的應用程序來說不是必需的,或者您需要添加其他索引,但這應該是一個很好的起點。 您沒有指定您正在使用的數據庫,但我將假設您使用LAMP堆棧。 以下是通過MySQL創建索引的信息。 用戶表中用戶名的唯一索引示例如下:
CREATE UNIQUE INDEX idx_unq_user_username ON user(username);
對於trival示例,它可能看起來像很多表,但在關系數據庫中,您通常希望盡可能地規范化表。 當您擁有常見的查詢時,您可以創建視圖,使用簡單的查詢訪問數據。 以這種方式設置表的另一個方面是,它允許您輕松地在有意義的位置添加列。 在您的初始架構中,如果您將city存儲在用戶表中,然后想要添加lat / long,則會開始使您的users表看起來越來越像一個位置表,其中隨意放置用戶信息。
規范化在數據庫級別做了很好的事情,例如允許更改數據以很少的實際更新傳播,有助於減少數據密度以減少滿足查詢的I / O要求和數據完整性。
解決方案2
這將使DB升至第三范式(更高更好),其中解1是第二范式。
內聯合的東西,很可能是這樣的:
Select * from usertable inner join hobbiestable on usertable.id = hobbiestable.id
1 - 用戶表(ID,名稱,城市)
2 - HOBBIES TABLE(ID,Name)
3 - USERSTOHOBBIES TABLE(UserID [外鍵],HobbyID [外鍵])
而且您需要創建適當的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.