php - 在表之间移动一行

标签 php mysql

我想将一行从 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/

相关文章:

mysql - .Net 应用程序处理 SQL 语句时无法使用系统

php - Laravel @foreach 在 Blade 中导致错误

java - 在联合表上使用 Specifications 和 CriteriaQuery 的 Spring JPA

php mysql 从下拉列表中获取值打印到屏幕

php - 基于键将 5 个数组与 php 组合

php - 如何获取php变量中选定的下拉项

mysql - 一次查询多项数据校验

php - 使用 PHP 和 MYSQL 对已知列进行搜索

PHP 简单 HTML DOM 解析器 - RSS 中的链接元素

php - MySQL 日期格式