views:

178

answers:

2

I was wondering if you can specify the order in which table definitions and data fixtures are loaded using the CLI. My problem is that I have two tables, each having a foreign key constraint pointing to the other, so one of the constraints needs to be added after a record has been added. Or maybe there's a better way of doing this...I'm no db expert and my head is fuzzy today.

Schema:

CREATE TABLE clients (
  id INT AUTO_INCREMENT,
  name VARCHAR(255), address VARCHAR(255), 
  primary_contact_user_id INT  # References a user record in the users table
  ...
);

CREATE TABLE users (
  id INT AUTO_INCREMENT,
  username VARCHAR(255),
  client_id INT  # References a client record in the clients table
  ...
);

ALTER TABLE clients 
  ADD CONSTRAINT clients_primary_contact_user_id_users_id 
    FOREIGN KEY (primary_contact_user_id) REFERENCES users(id);

ALTER TABLE users 
  ADD CONSTRAINT users_client_id_clients_id 
    FOREIGN KEY (client_id) REFERENCES clients(id);
+1  A: 

I'm also not a DB expert, but I do spend a lot of time working with them. I believe the circular reference is actually incorrect.

Regardless of whether DB theory sanctions it or not, you could get one field though a join to another table, so it is an unnecessary circular reference. I'd suggest that you eliminate one and alter any queries to reflect this change.

Based on a guess, I'd suggest that you eliminate primary_contact_user_id, as that almost sounds like a possible many-to-many relationship where a single item is elected as "primary"...

If you feel this design is necessary, can you please explain why?

Frank V
Thanks for the suggestion, that's actually what I was just thinking after looking at my question. And no, it's not crucial to keep the design as it is.
rr
A: 

put the INSERT statements between the CREATE TABLE and ALTER TABLE statements.

longneck