更新后,一列将该行移动到sql中的另一个表

时间:2015-03-12 07:17:48

标签: mysql database codeigniter

如何在完成更新功能后将一行从table1移动到table2。

table1:mem_id,st_id,name,num,status,date

table2:mem_id,st_id,name,num,status,date

当我从table1更新状态时,该行应该移到codeigniter中的table2。

2 个答案:

答案 0 :(得分:1)

创建示例表

create table table1(mem_id INT, st_id INT, name CHAR(30), num INT, status INT, date_en DATE);

再创建一个具有与上述相同定义的表格

create table table2 like table1;

在table1中插入一些示例数据

INSERT INTO table1 VALUES(1,1,'Vinay',1,1,CURDATE());

SELECT * FROM table1;
+--------+-------+-------+------+--------+------------+
| mem_id | st_id | name  | num  | status | date_en    |
+--------+-------+-------+------+--------+------------+
|      1 |     1 | Vinay |    1 |      1 | 2015-03-12 |
+--------+-------+-------+------+--------+------------+
1 row in set (0.00 sec)

在table1上创建触发器

DELIMITER //
CREATE TRIGGER table_after_update AFTER UPDATE ON table1 FOR EACH ROW
BEGIN
    INSERT INTO table2 VALUES(old.mem_id,old.st_id,old.name,old.num,old.status,old.date_en);
END // 
DELIMITER ;

检查您的更新查询

UPDATE table1 SET status = 55 WHERE mem_id = 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

检查来自table1和table2的数据

SELECT * FROM table1;
+--------+-------+-------+------+--------+------------+
| mem_id | st_id | name  | num  | status | date_en    |
+--------+-------+-------+------+--------+------------+
|      1 |     1 | Vinay |    1 |     55 | 2015-03-12 |
+--------+-------+-------+------+--------+------------+
1 row in set (0.00 sec)

数据已插入表2

SELECT * FROM table2;
+--------+-------+-------+------+--------+------------+
| mem_id | st_id | name  | num  | status | date_en    |
+--------+-------+-------+------+--------+------------+
|      1 |     1 | Vinay |    1 |      1 | 2015-03-12 |
+--------+-------+-------+------+--------+------------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

您可以使用后插入触发器执行此操作并将其放在表1上。

这样的东西可以在触发器中起作用:

INSERT INTO table2 (status) SELECT status FROM table1 WHERE (*if you need to use any conditions*)

DELETE FROM table1 WHERE (where clause here)