1

I have two tables: one and two. I have a primary key (id) in table one.

Table One:

CREATE TABLE `one` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`first_name` varchar(10) NOT NULL,
`last_name` varchar(10) NOT NULL,
`salary` int(100) NOT NULL,
`login_date_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1

id    first_name    last_name    salary  login_date_time 

Table Two

CREATE TABLE two AS (SELECT id,salary ,CONCAT(first_name, ',', last_name) AS Name from one)

Now adding the foreign key to id as:

ALTER TABLE two
ADD CONSTRAINT `0_38775` FOREIGN KEY (id)
REFERENCES one(id) ON DELETE CASCADE ON UPDATE CASCADE

the table two comes as with the values from table one:

id    salary       name  

Now to maintain referential integrity, how to update the values of table two when table one is updated. And also I cannot delete rows from table one and cannot insert rows to table two.

How can I update all the columns of table two when table one is updated/inserted. or insert explicitly into table two

4
  • 1
    What scripts are you running, and what errors are you getting? For inserting, you should be able to insert into one first, and then two. For deleting, if you delete a row from one, it will automatically delete any associated rows from two.
    – Joe
    Dec 30, 2013 at 14:59
  • i dont have any values in table one but when i enter the value in table one its not inserted in table 2
    – black
    Dec 30, 2013 at 15:09
  • 1
    A constraint doesn't automatically insert records; you would need a trigger for that.
    – Joe
    Dec 30, 2013 at 15:11
  • so we can write an update trigger to do it without mentioning the ON UPDATE and DELETE cascade or have to mention it to do the trigger work?
    – black
    Dec 30, 2013 at 18:18

1 Answer 1

2

Well, for the case of delete, when you delete the row from table 1, all the rows corresponding to that id will be deleted from table 2.

In case of update, if you want first name and last name to be updated in table 2 when they are altered in table 1 then you will have to write an update trigger for that.

2
  • thanks! to do it work we can write an update trigger. but should we mention that ON UPDATE cascade when creating keys to make the trigger work or its not neccessary?
    – black
    Dec 30, 2013 at 18:20
  • 1
    It is not necessary. Update trigger will take care of all the update operations. Dec 31, 2013 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.