English 中文(简体)
如何知道在使用“ 重复按键更新” 时插入或更新一行?
原标题:How to know if when using "on duplicate key update" a row was inserted or updated?
  • 时间:2012-05-22 20:07:00
  •  标签:
  • mysql

我们有一个数据库 每天在午夜更新 与一个cronjob, 我们从新的数据 从外部的XML。

我们所做的是,我们插入所有新的内容,如果出现重复的关键,我们更新这个领域。

INSERT INTO table (id, col1, col2, col3)
values (id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
ON DUPLICATE KEY UPDATE 
col1 = VALUES (col1), 
col2 = VALUES (col2), 
col3 = VALUES (col3);

我们想知道的是哪些行实际上已经插入了, 意思是我们希望有一份新项目列表。 是否有可以返回新插入的查询? 基本上我们需要获得所有新的 ID, 而不是新插入的数量 。

谢谢 谢谢

最佳回答

添加 update_count INT NULL DUFAUL 1 列并更改查询:

INSERT
INTO    table (id, col1, col2, col3)
VALUES
(id_value, val1, val2, val3),
(id_value, val1, val2, val3,),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
ON DUPLICATE KEY
UPDATE 
        col1 = VALUES (col1), 
        col2 = VALUES (col2), 
        col3 = VALUES (col3),
        update_count = update_count + 1;

您也可以在 BEFORE UPDATE 触发器中加载它,这样您就可以保留查询原样。

问题回答

我可以说我在PHP里是怎么做到的:

(1) 简单查询 SELECT MAX(id) 并记住在插入重复时从表格中到 $max_id 。

然后在更新过程中收集受影响行的标识(没有新的或已经存在的行):$[] = Mysql_插入_id ();

3) 然后用 $dreed_row = 最大(美元)-$max_id;

4) 更新的行 = 计数($ids_srt)- $ 插入的行

$max_id = mysql_query("SELECT MAX(id) from table");
$max_id = mysql_result($max_id, 0);

// !!! prepare here  insert on duplicate  query in a cycle

$result=mysql_query($query);
$ids[] = mysql_insert_id();

// finish inserting and collecting affected ids and close cycle

$inserted_rows = max($ids)- $max_id;
$updated_rows = count($ids)- $inserted_rows




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签