Traveling_Monk
Traveling_Monk

Reputation: 788

How do i add foreign keys to two Innob tables so that they autoupdate each other?

I have two tables users and lead_contacts which have similar data. When somebody buys a product they become a user. How should I modify the two create staements below so:

Upvotes: 1

Views: 456

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562791

I think you misunderstand how foreign keys work.

A reference from leads to users means that a row must already exist in users before a row in leads can reference it.

There's no way in SQL to make a dependent table automatically create a row in its parent table on demand.

You could do this with a trigger, I suppose. But not a foreign key constraints. Besides, the values to fill into the parent table must come from somewhere. Either you need to specify them in an INSERT statement in your application or in a trigger, or else use the defaults defined for each column in the users table. Given that you have a unique constraint on users.username, I don't think this would be possible from a trigger.


Re: your followup question in the comment:

No, a foreign key can't do what you're describing. When you modify info in the leads table (the table with the foreign key), the only thing a foreign key can do is prevent the modification if you try to change the leads.user_id column to a value that is not found in the users table.

The foreign key in the child (leads) table can't change anything in the parent (users) table.

I'm not sure what is the source of your mistaken understanding. Did you read it somewhere or see someone do something like this?

Upvotes: 3

Related Questions