Reputation: 1498
Lets say i got two tables in mysql.
1. person (id, name, lastname) - Image
2. someothertable (id, name, lastname, action, quantity) - image
I wanted to ask, if its really bad practice, to update both tables at once? For example if someone updates the last name of Robert Jackson to "Smith" then do 2 queries:
mysql_query("UPDATE person SET lastname = '$lastname' WHERE id = '$id'");
mysql_query("UPDATE someothertable SET lastname = '$lastname' WHERE name = '$name' AND lastname = '$oldlastname'");
Assuming for now, you wont meet 2 same names and surnames (its just an example).
Is it strongly recommended, to join those two tables when displaying data from tables, and change last name only in person
table?
I didn't have need to use join
before (never had databases big enough), and I just started to wonder if there is another way to do this (than 2 queries). Using join
will require some code changing, but i am ready to do it, if its right thing to do.
Upvotes: 0
Views: 214
Reputation: 12508
One option would be to make someothertable
have a foreign key constraint on the lastname
field in Person
. You could apply an update trigger so it would automatically cascade.
Here is an example below:
Alter table someothertable add constraint foreign key (lastname) references Person (lastname) on delete cascade on update cascade;
A generic version of that can be seen below:
Alter table [table-name] add constraint foreign key (field-in-current-table) references [other-table-name] (field-in-other-table) on delete cascade on update cascade;
This can be applied to any field in any table. You can then set the triggers to be appropriate for you. Here is a reference link.
Have you considered normalization?
Another option would be to assign each person
in the Person
table a uniqueID (i.e. PersonID
). Now in all your other tables you where you reference a person
you reference them by the unique id. This adds many advantages:
1) It keeps the data normalized 2) It maintains data integrity 3) No need for updates, triggers, or cascades 4) A change would only be required in one place
Hope this helps. Best of luck!
Upvotes: 1
Reputation: 880
Using a join
is not a function of how big your databases are, it's about normalization and data integrity. The reason you would have lastname
in only one table is so that there's no need to worry about keeping values in sync. In your example, if those calls are in a single transaction, then they should stay in sync. Unless one of them is changed somewhere else, or manually in the database.
So an option for you would be to have these tables:
person (id, name, lastname)
someothertable (id, person_id, action, quantity)
Upvotes: 2