简体   繁体   English

结果不在csv文件中时,从表中删除行

[英]Delete rows from table when the result are not in a csv file

I have this code to insert values from a csv file. 我有这段代码从csv文件插入值。 Some values are updated when the row already exist at the database. 当数据库中已存在该行时,将更新某些值。 Just how I want it to be. 就是我想要的样子。

INSERT INTO test_table (`id`,`order_id`,`quantity`,`price`,`order_date`,`shipping_date`)
                    VALUES ('$orderId', '$quantity', '$price', '$orderDate', '$shippingDate')
                    ON DUPLICATE KEY UPDATE `order_date` = '$orderDate', `shipping_date` = '$shippingDate'"

But when the row is not at the csv it must be deleted from the database. 但是,当该行不在csv上时,必须将其从数据库中删除。 For example: 例如:

csv file: CSV文件:

order_id  quantity price order_date shipping_date
1          10      1.00  2016-10-5  2016-10-6

I run the script and the result from the csv is added to the database. 我运行脚本,并将csv的结果添加到数据库中。 But my next csv contains this: 但是我的下一个csv包含以下内容:

order_id  quantity price order_date shipping_date
2         120      2.00  2016-10-8  2016-10-10

A new row must be added. 必须添加新行。 No problem, my query is fine. 没问题,我的查询很好。 But the row with order_id 1 is gone at the csv. 但是具有order_id 1的行在csv消失了。 That row must be deleted from the database. 该行必须从数据库中删除。 How can I do this? 我怎样才能做到这一点? Is this possible to do with my query? 这可能与我的查询有关吗? Or do I need another one? 还是我需要另一个?

You will need to add a field to store "version" of your update. 您将需要添加一个字段来存储更新的“版本”。

ALTER  TABLE test_table ADD version BIGINT DEFAULT 0;

Before doing INSERT , assign $vers = time() in PHP. 在执行INSERT之前,在PHP中分配$ vers = time()。 Old rows will contain version value smaller than current version number. 旧行将包含小于当前版本号的版本值。

Change your SQL to update version field in both INSERT and ON DUPLICATE parts of your query. 在查询的INSERT和ON DUPLICATE部分中更改SQL以更新version字段。

INSERT INTO test_table (`id`,`order_id`,`quantity`,`price`,`order_date`,`shipping_date`,`version`)
                    VALUES ('$orderId', '$quantity', '$price', '$orderDate', '$shippingDate','$vers')
                    ON DUPLICATE KEY UPDATE `order_date` = '$orderDate', `shipping_date` = '$shippingDate', `version` = $vers"

Do import. 做进口。

Then after import is completed, delete old data 然后,在导入完成后,删除旧数据

DELETE FROM test_table WHERE version < $vers

Should do the trick. 应该做到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM