繁体   English   中英

数据库设计选择性能

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM