1

Let me explain what I need and canot get :( I have to DB one i main the other is just getting part of data from the firs one.

This is my code:

foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id_product`, `date`, `available`, `published`) VALUES ('".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}

The problem is that this multiples the record in DB2 so I am now in millions!!! Its set up as cron job on 1h basis.

What I need is ether it checks what is existing and don't touch it or if need on update or insert.

The other solution would be to delete the whole table in DB2 then to insert a fresh one from DB1

4

3 回答 3

2

您可以像这样简化查询:

INSERT INTO tbl2 (column1, column2)
SELECT column1, column2 FROM tbl1
ON DUPLICATE ...

请参阅文档

于 2013-05-13T15:19:51.880 回答
1

您正在寻找 MySQL 的专有 REPLACE 命令。它具有与常规 INSERT 相同的语法,但它在插入之前检查重复的主键,如果发现它会执行 UPDATE 代替:

REPLACE 的工作方式与 INSERT 完全相同,只是如果表中的旧行与 PRIMARY KEY 或 UNIQUE 索引的新行具有相同的值,则在插入新行之前删除旧行。

当然,您必须在您的表上定义一个唯一的 PK/索引,以允许此功能工作。

于 2013-05-13T15:20:07.867 回答
0

这是一个更新!

我解决了这个问题:)

感谢 Niels,因为他让我重新思考了我的策略,所以解决方案很简单。

在 DB1 和 DB2 中有和 ID 归档 A 添加 $aa5=$rowi['id']; 这样就可以使 ON DUPLICATE KEY UPDATE 正常工作!

foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa5=$rowi['id'];
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id`,`id_product`, `date`, `available`, `published`) VALUES ('".$aa5."','".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id` = '".$aa5."',`id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}

它似乎工作正常!:)

于 2013-05-13T16:55:20.073 回答