我遇到了这个MySQL查询的问题 -
UPDATE users
SET field = 1
WHERE time BETWEEN '_time1_' and '_time2_'
AND count(email) > 1;
它说我在count()处使用group-by函数时出错。我也试过HAVING COUNT。我不确定如何指定此查询,实际答案可能比我想象的更嵌套。
count(列)似乎适用于SELECT但不适用于UPDATE。
答案 0 :(得分:1)
假设您要在time1
和time2
内更新多次出现的记录,这应该可以解决问题:
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
查询,上述查询将返回将要更新的所有记录。