Question

I'm currently working with a client that wants their database to duplicate info into a second table in a different format when it is initially inserted.

Basically like the following:

Table 1

| ID |  NAME    | EMAIL  |  password  |  
--------------------------------------
|  1 |    david | x@x.co |  asx234    | 
|  2 |  anthony | y@x.co |  24gss3    |
|  3 |  jillian | z@x.co |  hdfg5d    |

Every time a row gets inserted into table 1 they also want to take that information from table 1 and add it to Table 2

Table 2

| ID |  NAME    | EMAIL  |  password  |  signature  |  level  |  lastenter  |  register_date  |
-----------------------------------------------------------------------------------------------
|  1 |    david | x@x.co |  asx234    |  text       |  3      |  0000-00-00 |  Date of insert | 
|  2 |  anthony | y@x.co |  24gss3    |  text       |  3      |  0000-00-00 |  Date of insert |
|  3 |  jillian | z@x.co |  hdfg5d    |  text       |  3      |  0000-00-00 |  Date of insert |

How do I set up a trigger to insert the data into Table 2 whenever a row is inserted into table 1?

Thanks!

Était-ce utile?

La solution

Some thoughts below, but the trigger would look something like this:

 DELIMITER $$

 DROP TRIGGER IF EXISTS trgMyNewTrigger $$

 CREATE TRIGGER trgMyNewTrigger AFTER INSERT ON Table1
 FOR EACH ROW
 BEGIN
     INSERT into Table2 (ID,NAME,EMAIL,`password`,signature,`level`,lastenter,register_date) VALUES (
        new.ID, new.NAME, new.EMAIL, new.password, 'text', 3, '0000-00-00', CURDATE() );
 END $$

 DELIMITER ;

This is not a great solution. Triggers in general can cause some nasty issues and limit your capabilities down the road. It would be better to reconsider the design of the table to be inclusive of the data you need, have the application perform the extra step or use some sort of ETL process to get the data at set intervals.

I will all assume the clear text passwords are for the example.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top