我想将一行从 posts
移至 archive
。
两个表具有相同的列。
$st = $db->query("select * from posts where id = " . $id);
while ($row = $st->fetch()){
$date = $row['date']; ...
$sql = "insert into archive (date,...) values (:adate,...)";
$st = $db->prepare($sql);
$st->execute(array(
":adate" => $date, ...
$st = $db->query("delete from posts where id = " . $id);
id
列在两个表上都会自动递增。
是否有更短的方法来执行此操作,因为每个表上有 14 列?
最佳答案
只要列具有相同的类型和相同的顺序,您就可以insert into archive select * from posts where id = :id
。但是,这将插入到具有相同 id 的 archive
中。
MariaDB [temp]> select * from posts;
+------+-------+-------+
| id | a | b |
+------+-------+-------+
| 2 | test3 | test4 |
| 1 | test | test2 |
+------+-------+-------+
2 rows in set (0.00 sec)
MariaDB [temp]> select * from archive;
Empty set (0.00 sec)
MariaDB [temp]> insert into archive select * from posts where id = 2;
Query OK, 1 row affected (0.05 sec)
Records: 1 Duplicates: 0 Warnings: 0
MariaDB [temp]> select * from archive;
+------+-------+-------+
| id | a | b |
+------+-------+-------+
| 2 | test3 | test4 |
+------+-------+-------+
1 row in set (0.01 sec)
MariaDB [temp]>
如果你想让 id 列正常自动递增,你必须选择每一列,例如 insert into archive (date,...) select (date,...) from posts where id = :id
MariaDB [temp]> select * from posts;
+------+------+-------+
| id | a | b |
+------+------+-------+
| 1 | test | test2 |
+------+------+-------+
1 row in set (0.00 sec)
MariaDB [temp]> select * from archive;
+----+-------+-------+
| id | a | b |
+----+-------+-------+
| 2 | test3 | test4 |
+----+-------+-------+
1 row in set (0.00 sec)
MariaDB [temp]> insert into archive (a, b) select a, b from posts where id = 1;
Query OK, 1 row affected (0.02 sec)
Records: 1 Duplicates: 0 Warnings: 0
MariaDB [temp]> select * from archive;
+----+-------+-------+
| id | a | b |
+----+-------+-------+
| 2 | test3 | test4 |
| 3 | test | test2 |
+----+-------+-------+
2 rows in set (0.00 sec)
MariaDB [temp]>
关于php - 在表之间移动一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49702251/