views:

51

answers:

1

I don't even know if that's the right term.

May it be known that I'm a major novice!

I have three tables: users, profiles, and survey. Each one has user_id as it's first field, (auto-increment for users), and they're all tied by a foreign key constraint, CASCADE on DELETE.

Currently, for each user, let's say user_id 1, they have a corresponding db entry in the other tables. For profiles it lists all their information, and the survey table holds all their survey information.

Now I must change things...darn scope creep. Users need the ability to have multiple survey results. I imagine that this would be similar to a comment table for a blog...

My entire app runs around the idea that a single user is linked to a constraining profile and survey.

How should I structure my db?

How should I design my app's db so that a user can have multiple tests/profiles for the test?

Please assist! Any advice, information and personal-knowledge is appreciated!

Right now the only way I know how to accompany my client is to create a pseudo-user for each test (so unnecessary) and list them in a view table (called "your tests")-- these are obtained from the db by saying: where user_id=manager_id

+2  A: 

Right now, survey has a foreign key to user, identifying the user who took the survey. This is good, and does not change.

But add an autoincrement primary key to survey (and to profile, too). Now a user can have multiple surveys. Each individual survey has its key, and its taker is identified by the user foreign key.

To find all surveys for all users:

select a.*, b,* 
from user a 
join survey b on (b.user_id = a.user_id);

To find all surveys for one user:

select a.*, b,* 
from user a 
join survey b on (b.user_id = a.user_id)
where a.user_id = some_user_id;

To just get the survey data, just select b.* only. For example:

select b.* 
from survey b on 
where a.user_id = ( select user_id from user a where a.name = 'Bob' );

Again, all you need to do is add a primary key (which should be an autoincrement) to survey.

tpdi
I think I understand...I'll have more questions tomorrow!
Kevin Brown
This is working...What do I do if I want to delete a survey? The way things work (maybe I haven't communicate correctly), I delete all surveys b/c they're tied to the user_id.
Kevin Brown
To delete (or select, or update) all surveys for a user, use the user_id: e.g, delete from survey where user_id = x; or, delete the user and let delete cascade on the fk delete them for you. If you want to delete (or select,or update) only a single survey, use that survey's id.
tpdi
Fantastic. You've been a great help!
Kevin Brown