gpt4 book ai didi

mysql - 通过 LEFT JOIN 优化 SQL 子查询

转载 作者:行者123 更新时间:2023-11-29 04:39:36 25 4
gpt4 key购买 nike

我想根据不存在于 uniqueEntries 中的 actualEntries User_ID,将 actualEntries 表中的所有记录插入到 uniqueEntries 表中。

我从一个包含 NOT IN 子查询的 sql 子句开始,它非常慢(当操作 400K 记录时),然后将它变成一个 LEFT JOIN 子句,但是速度并没有提高。

以下是我的原始 sql 子句,其中包含 NOT IN 子查询:

INSERT INTO uniqueEntries 
SELECT *
FROM actualEntries
WHERE actualEntries.User_ID NOT IN (
SELECT uniqueEntries.User_ID
FROM uniqueEntries
)
GROUP BY User_ID"

下面是转换为LEFT JOIN后的sql子句:

INSERT INTO uniqueEntries 
SELECT actualEntries.*
FROM actualEntries
LEFT JOIN uniqueEntries
ON uniqueEntries.User_ID = actualEntries.User_ID
WHERE uniqueEntries.User_ID IS NULL
GROUP BY User_ID

当我对 50 条记录运行这两个查询时,它们会立即完成,但是当我对 40 万条记录运行它们时,它们不会完成。

完成此操作的最快方法是什么?

更新/解决方案:根据@Rahul、@Steve E 和@fhthiella,我更新了 LEFT JOIN 如下,并将 470K 记录的处理时间减少到 2 分钟。

INSERT INTO uniqueEntries 
SELECT actualEntries.*
FROM actualEntries
LEFT JOIN uniqueEntries
ON uniqueEntries.id = actualEntries.id
WHERE uniqueEntries.User_ID IS NULL GROUP BY User_ID

最佳答案

在 uniqueEntries.User_ID 上放置一个唯一键或主键。然后

INSERT IGNORE INTO uniqueEntries 
SELECT actualEntries.*
FROM actualEntries

IGNORE 子句将使MySQL 跳过插入过程中的错误。这就是the manual说:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.

关于mysql - 通过 LEFT JOIN 优化 SQL 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com