在表之间移动一行

时间:2018-04-06 23:28:37

标签: php mysql

我想从postsarchive移动一行。 两个表都有相同的列。

$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列?

2 个答案:

答案 0 :(得分:1)

只要列的类型相同且顺序相同,您就可以执行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]> 

答案 1 :(得分:0)

实际上,我建议您使用以下方法:

$ids = array(3, 7, 15, 31, 45);
$clause = implode(',', array_fill(0, count($ids), '?'));

$stmt = $mysqli->prepare('INSERT INTO Archive SELECT Field1, Field2, Field3 FROM Posts WHERE `id` IN ('.$clause.');');
call_user_func_array(array($stmt, 'bind_param'), $ids);
$stmt->execute();

$stmt = $mysqli->prepare('DELETE FROM Posts WHERE `id` IN ('.$clause.');');
call_user_func_array(array($stmt, 'bind_param'), $ids);
$stmt->execute();

使用IN语句可以避免对每个ID使用单个查询,而INSERT INTO语句可以避免对每个插入执行选择。总的来说,应该改进流程的性能。

最重要的是,我建议您在TRANSACTION内执行所有操作,以便在其中一个查询失败或服务器遇到问题时,您的表格不会搞砸。< / p>