Hi I am new to databases in general, so forgive my noob question below, but I really do need help.
I have designed a database with 4 tables. I have created an application in C# which will store some values in these 4 tables during the course of the application running. However, this is all working fine when there is only one user of the application, but if more that one user is going to use the same application running in an ASP.NET page, then they will be accessing and altering the data in the 4 tables, and problems will soon arise.
My question is, how do I prevent this from happening? I want each user to have their own unique username and then use that to differentiate them in the tables but my knowledge of databases is limited to know how to achieve this. Please help?
Supposing you have the following table today:
FavoriteFood ————————————— FoodId FoodName
And it lists all of your favorite foods. But then you decide you'll let me use your database to store my favorite foods too. Since you don't care about my favorite foods, and I don't care about yours, you need a way of keeping them separate. First, you'll create a User
table:
User ————————— UserId UserName FirstName LastName
Then, you need to relate the User
table to the FavoriteFood
table. One way of doing this would be to add a Foreign Key to the FavoriteFood
table. Give it a new field called UserId
:
FavoriteFood ————————————— FoodId UserId FoodName
Then you can get just the food for a single user by adding a WHERE
clause to your SQL code:
SELECT FoodName
FROM FavoriteFood
WHERE UserId = @UserId
That could be ok, but I'm not satisfied with it. This database is not normalized! Suppose, you later want to store calorie information about your foods. You add a field called calories
to your FavoriteFoods
table. As you are populating that field with data, you notice that you are putting in the same data multiple times. All of your users like bananas, so you have as many entries in your table for bananas as you have users. You have to enter the exact same calorie information over and over again. Instead, you should have all the information for a food in the table just once, and use a completely separate table to map food to users:
Food ————————— FoodId FoodName Calories FavoriteFood ————————————— FoodId UserId
Use a join to get the favorite food for a user:
SELECT f.FoodName
,f.Caloires
FROM Food f
JOIN FavoriteFood a ON a.FoodId = f.FoodId
WHERE a.UserId = @UserId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.