我试着运行这个查询:
update table1 A
set number = (select count(distinct(id)) from table2 B where B.col1 = A.col1 or B.col2 = A.col2);
但它需要永远 bc table1 有 1,100,000 行,table2 有 350,000,000 行。
有没有更快的方法在 R 中执行此查询?还是在 python 中?
最佳答案
我用三个子查询而不是一个子查询重写了您的查询 - 使用 UNION
和两个 INNER JOIN
语句:
UPDATE table1 as A
SET number = (SELECT COUNT(DISTINCT(id))
FROM
(SELECT A.id as id
FROM table1 as A
INNER JOIN table2 as B
ON A.col1 = B.col1) -- condition for col1
UNION DISTINCT
(SELECT A.id as id
FROM table1 as A
INNER JOIN table2 as B
ON A.col2 = B.col2) -- condition for col2
)
我的笔记:
- 更新
table1
中的所有行看起来不是一个好主意,因为我们必须触及 1.1M 行。可能,用于存储number
的另一种数据结构会有更好的性能 - 尝试在不更新
table1
的情况下运行部分查询(仅括号中的部分查询 - 如果您需要更通用的 SQL 查询优化方法,请查看
EXPLAIN
:https://dev.mysql.com/doc/refman/5.7/en/using-explain.html
关于python - 在 R 中执行 mysql 更新查询的任何更快的方法?在 python ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063814/