开发者

Displaying name from ID of lookup tables - design Q

开发者 https://www.devze.com 2023-02-10 05:40 出处:网络
I am sure this is a basic question but I am new to SQL so anyways, for my user profile I want to display this: location = \"Hollywood, CA - USA\" if a user lives in Hollywood. So I assume in the user

I am sure this is a basic question but I am new to SQL so anyways, for my user profile I want to display this: location = "Hollywood, CA - USA" if a user lives in Hollywood. So I assume in the user table there will be 1 column like current_city which will have ID say 1232 which is a FK to the city table where city_name for this PK = Hollywood. Then connect with the state table and the country table to find the names CA and USA as the city lookup table will only store the IDs (like CA = 21 and USA = 345)

Is this the best way to design the table OR I was thinking should I add 2 columns like city_id and city_name to the user_table. And also add country_id, country_name, state_id, state_name to the开发者_Go百科 city table. This way i save on trips to other parent tables just to fetch the name for the IDs.

This is only a sample use case but I have lots of lookup ID tables so I will apply the same principle to all tables once i know how to do it best. My requirement is scalability and performance so whatever works best for these is what i would like.


The first way you described is almost always better.

Having both the city_id and city_name (or any pair of that kind) in the users table is not best practice since it may cause data discrepancies - a wrong update may result in a city_id that does not match the city_name and then the system behavior becomes unexpected.

As said, your first suggestion would be the common and usually the best way to do this. If table keys are designed properly so all select statements can use them efficiently this would also give the best performance.

For example, having just the city_name in the users table would make it a little quicker to find and show the city for one user, but when trying to run other queries - like finding all users in city X, that would make much less sense.

You can find a nice series of articles for beginners about DB normalization here: http://databases.about.com/od/specificproducts/a/2nf.htm. This article has an example which is very much like what you are trying to achieve, and the related articles will probably help you design many other tables in your DB.

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消