views:

30

answers:

1

This is how my tables look:

tableMembers | memberID as primary key

tableAddress | addressID as primary key references memberID

tableSubscription | subsID as primary key references memberID

This database is for a subscription site. Basically, if a row is inserted into tableMembers, a corresponding row is inserted to each of the other tables.

I set up foreign keys for the last two tables so I can access them in relation to tableMembers. Basically if I access a row from tableAddress I do:

SELECT * FROM tableAddress WHERE addressID = (SELECT memberID FROM tableMembers WHERE uname = 'John'); 

The problem with my setup is that, when synchronization of ID's gets messed up, foreign keys would no longer work. Say, when I insert a row into tableMembers and then tableSubscription becomes dysfunctional for few seconds for some weird reasons? Or in case of a user signing up (latest memberID becomes = 2), say he/she doesn't subscribe which leaves subsID (which remains = 1) unsynchronized with memberID. And later on, a new user signs up (latest memberID becomes = 3) and subscribes (subsID becomes = 2). That makes my query above obselete. How do I prevent this kind of scenario? Or please enlighten me if you think I don't understand the concept of foreign keys.

+2  A: 

Make sure that only one of the tables have an autoincrementing id. The others should get their id from the insert query, from the application code, to make sure they are for the correct member.

In pseudo-code:

  1. User signs up and get an autoincremented id of 3.
  2. Check the id with last_insert_id()
  3. User subscribes to something. The id in the tableSubscription table should be set by your application code to the value you got earlier.
Emil Vikström
Edit:Never mind. Thanks!
Joann