使用WHERE时间BETWEEN次和COUNT(列)> 1更新表

时间:2015-05-05 21:16:04

标签: mysql

我遇到了这个MySQL查询的问题 -

UPDATE users

SET field = 1

WHERE time BETWEEN '_time1_' and '_time2_'

AND count(email) > 1;

它说我在count()处使用group-by函数时出错。我也试过HAVING COUNT。我不确定如何指定此查询,实际答案可能比我想象的更嵌套。

count(列)似乎适用于SELECT但不适用于UPDATE。

1 个答案:

答案 0 :(得分:1)

假设您要在time1time2内更新多次出现的记录,这应该可以解决问题:

UPDATE users
SET field = 1
WHERE
  time BETWEEN '_time1_' AND '_time2_'
  AND (
    SELECT COUNT(email)
    FROM users AS ucount
    WHERE ucount.time BETWEEN '_time1_' AND '_time2_'
      AND users.email = ucount.email
    GROUP BY ucount.email
  ) > 1

记住:在执行有风险的批量更新之前总是备份您的数据,或者在事务中执行此操作,并确保在提交之前完成此操作。

您还可以通过以下方式检查您要更新的内容:

SELECT * -- Just replace 'UPDATE' for 'SELECT * FROM'
FROM users
-- SET field = 1 -- And comment 'SET' to perform the SELECT
WHERE
  time BETWEEN '_time1_' AND '_time2_'
  AND (
    SELECT COUNT(email)
    FROM users AS ucount
    WHERE ucount.time BETWEEN '_time1_' AND '_time2_'
      AND users.email = ucount.email
    GROUP BY ucount.email
  ) > 1

如果您运行UPDATE查询,上述查询将返回将要更新的所有记录。