【问题标题】:Move from one table to another从一张桌子移动到另一张桌子
【发布时间】:2011-10-09 16:52:12
【问题描述】:

我需要将一些数据从表移动到存档表。

现在我这样做了:

$sql = 'INSERT INTO history_products 
         SELECT * FROM products WHERE category_id='.$id;

然后我从产品表中删除数据。

$sql_delete = 'DELETE FROM products WHERE category_id = '.$id;

每个产品都有一个唯一的 ID。 但我想以一种安全的方式做到这一点,现在即使没有在 history_products 中插入一行,该行也会从 products 表中删除。如果插入失败,我不想删除。

【问题讨论】:

    标签: php mysql database move


    【解决方案1】:

    我希望您有一个名为 id (ProduktID) 的字段,那么两个表中哪些产品必须具有相同的 id,以下应该可以工作。

    从 products.id IN 的产品中删除(从 history_products 中选择 history_products.id)

    【讨论】:

    • 我认为这样:DELETE FROM products WHERE category_id = $category_id AND products.id IN (SELECT history_products.id from history_products)
    • DELETE FROM products WHERE products.category_id = $category_id AND products.id IN (SELECT history_products.id from history_products and history_products.category_id = $category_id) 这将使 IN 集的计数更小可能整个执行速度快一点
    • 还是这样?:DELETE FROM products WHERE products.id IN (SELECT history_products.id FROM history_products WHERE category_id = $category_id) ?
    • 你是对的,我有一个 C&P 错误;)但我会在 Where's 中使用该类别
    【解决方案2】:

    如果使用唯一键,请删除产品中与历史表中具有相同键的所有记录。

    【讨论】:

    • 这意味着我必须在 INSERT 之后再进行一次选择才能插入所有行?!
    • 不,我认为他的意思是我所说的.. 在 DELETE 的 WHERE 子句中使用两个表中必须相同的唯一产品 ID
    • 不需要选择。只是在哪里删除。
    【解决方案3】:
    DELETE FROM products WHERE category_id IN (SELECT category_id FROM history_products)
    

    这只会删除 products 表中相应记录存在于 history_products 中的记录。

    【讨论】:

    • 这仍然会删除未移过的具有相同类别的记录。
    • 你仍在删除整个类别... mich 的方法是使用 productid 删除那些 id 在历史记录表中的产品
    • 好吧,将 category_id 更改为两边的主键字段 - 很简单。
    猜你喜欢
    • 2020-07-29
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2019-02-25
    • 2015-06-20
    • 2014-01-24
    相关资源
    最近更新 更多