我想过滤数据库记录,如果有重复记录,我会将记录标记为deleted = 1
。很遗憾,我无法正确更新我的记录,我确实尝试使用limit 1
来更新记录,但我只更新了1条记录,如果我没有使用limit 1
它将更新整个记录。
以上是我的数据库表,我需要做的是,假设有一堆不同point_id
的记录,我只过滤到1
。现在我想查询按日期ASC
排序的记录,并将所有记录更新为deleted = 1
期望最后一条记录。
这是我的源代码。我现在面临的问题是它将更新所有记录,如果我使用LIMIT 1
它只会更新1条记录。
while($total > 1){
$total--;
$sql = sprintf("SELECT *
FROM customers_profiles_game_logs
WHERE point_id='$points_filter_row[point_id]'
AND customer_id='$sql_customer_row[customer_id]'
ORDER BY date_created ASC");
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($query);
$num_rows = mysql_num_rows($query);
for ($i = 1; $i < $num_rows; $num_rows--) {
echo $sqli = sprintf("UPDATE customers_profiles_game_logs
SET deleted='1'
WHERE customer_id='$sql_customer_row[customer_id]'
AND point_id='$row[point_id]' LIMIT 1");
mysql_query($sqli) or die(mysql_error());
}
}
答案 0 :(得分:2)
你可以有一个子查询来获取要更新的记录并将其与表本身连接起来,例如。
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
WHERE customer_id = 1 -- <== ID HERE
) b ON a.customer_id = b.customer_id
AND a.date = b.date
SET a.deleted = 1
如果删除子查询中的WHERE
子句,则每个客户的所有第一条记录都将更新。
答案 1 :(得分:0)
你需要这个:
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
WHERE customer_id = 1 -- <== ID HERE
) b ON a.customer_id = b.customer_id
SET a.deleted = 1
另一种风格:
UPDATE customers_profiles_game_logs a
INNER JOIN
(
SELECT customer_id, MIN(date) date
FROM customers_profiles_game_logs
) b ON a.customer_id = b.customer_id
SET a.deleted = 1