如何:
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要求来满足查询和数据完整性。
使用相应的索引,这将在各个方面(速度,可维护性,一致性)是最好的解决方案。 – CodeCaster 2012-02-28 12:40:03
感谢您的帮助,我是一个新手,所以我想知道,如果查询性能好这一切的加入? – carma 2012-02-28 12:52:05
我不知道如何使用索引,但坦克 – carma 2012-02-28 12:55:10