我有一个MySQL UPDATE查询,需要很长时间才能完成。我错过了一种更简单的方法来获得相同的结果吗?
"UPDATE table2, table1
SET table2.id_occurrences = (SELECT SUM(IF(id = table2.id, 1, 0)) FROM table1)
WHERE table2.id = table1.id;"
table2
包含id
的所有可能值,每个值只有一条记录。table1
包含一些id
的值,但有一些值有多个记录。table2
中的记录,以显示id
中table1
的相应值的出现次数。上面的查询完成了这项工作,但是当table1包含500条记录和table2
30,000条记录时,大约需要3分钟。我有更大的表要处理,所以这太长了:)提前致谢。
答案 0 :(得分:6)
我认为你加入更新可能不是必要的......
UPDATE table2
SET table2.id_occurrences = (SELECT COUNT(*) FROM table1
WHERE table2.id = table1.id);
答案 1 :(得分:3)
避免子查询,使用连接:
UPDATE table2
LEFT JOIN table1 ON (table2.id = table1.id)
SET table2.id_occurrences = COUNT(table1.id)
GROUP BY table2.id
哦,UPDATE不支持GROUP BY。试试这个问题:
UPDATE table2
LEFT JOIN (
SELECT id, COUNT(*) AS cnt FROM table1 GROUP BY id
) AS t1
ON (table2.id = t1.id)
SET table2.id_occurrences = t1.cnt
答案 2 :(得分:1)
我会选择类似的东西:
UPDATE table2
SET id_occurrences = (SELECT count(*) FROM table1
WHERE table1.id = table2.id)
答案 3 :(得分:0)
UPDATE table2, table1
SET table2.id_occurrences = (SELECT SUM(IF(id = table2.id, 1, 0)) FROM table1)
WHERE table2.id in (select distinct table1.id from table1) AND table2.id = table1.id;