2012-02-28 71 views
0

出于性能,啥子是最好的数据库用户表的设计,零部件及市场时,我想用户过滤在特定城市特定的爱好是什么?数据库设计选择性能

的1 - N1表

用户表

ID ........ | NAME .. | CITY ..... |嗜好............................. |
VALUE | VALUE | VALUE | VALUE1,VALUE2,VALUE3 |


解决方案2 - N1表

用户表

ID ........ | NAME .. | CITY ..... | HOBBIY1 | HOBBIY2 | HOBBIY3 | HOBBIY4 | HOBBIY5 | HOBBIY6 |
VALUE | VALUE | VALUE | VALUE ... | VALUE .... | VALUE .... | VALUE .... | VALUE ... | VALUE ... |


SOLUTION 3 - N2表

1 - 用户表

ID ....... | NAME .. | CITY .... |
VALUE | VALUE | VALUE |


2 - 爱好TABLE

ID ....... | HOBBY |
VALUE | VALUE |


什么是最好的PHP查询列出一个城市的用户爱好?

回答

0

溶液2

那将解除DB到第三范式(越高越好),其中解决方案1是第二正常形式。

并与内部连接的东西,最有可能的是:

Select * from usertable inner join hobbiestable on usertable.id = hobbiestable.id 
2

如何:

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堆栈。这里是creating indexes via MySQL的信息。在用户表上的用户名的唯一索引的一个例子是:

CREATE UNIQUE INDEX idx_unq_user_username ON user(username); 

它可能看起来像很多的繁琐例如表,但在关系数据库中,你通常要尽可能正常化你的表可能。如果您有常见的查询,那么您可以创建视图,使数据可以通过更简单的查询访问。以这种方式设置表格的另一个方面是,它允许您轻松地添加列,使其有意义。在您的初始模式,如果用户表内存储的城市,然后想增加纬度/长,它开始让你的用户表看起来越来越像与用户信息的位置表随意放置在其内。

正火在数据库级别不美好的东西,以及像允许数据的变化非常少的实际更新传播,与数据的密度有助于降低I/O要求来满足查询和数据完整性。

+0

使用相应的索引,这将在各个方面(速度,可维护性,一致性)是最好的解决方案。 – CodeCaster 2012-02-28 12:40:03

+0

感谢您的帮助,我是一个新手,所以我想知道,如果查询性能好这一切的加入? – carma 2012-02-28 12:52:05

+0

我不知道如何使用索引,但坦克 – carma 2012-02-28 12:55:10

0

1 - 用户表(ID,名称,城市)


2 - 爱好TABLE(ID,姓名)


3 - USERSTOHOBBIES表(用户ID [外键],HobbyID [外键])

你还需要建立相应的索引。

+0

喜感谢您的帮助,但我已经编辑了问题,如果爱好是只有5我还要创造爱好特定的表或者是更好地创建5行用户表? – carma 2012-02-28 12:39:43

+0

是的,你仍然需要为业余爱好创建一个特定的表格。 – 2012-02-28 12:42:51