mysql - 如何加快 NOT IN 查询?
问题描述
我有以下查询:
SELECT images.id from images WHERE images.id NOT IN
(
SELECT
temp.target_id
FROM (
SELECT
images_user_groups.images_id AS target_id,
images_user_groups.user_groups_id AS source_id
FROM
images_user_groups
) AS temp
INNER JOIN
user_groups ON user_groups.id = temp.source_id
INNER JOIN
images ON images.id = temp.target_id
WHERE
user_groups.description LIKE "%Freigabe ins Presseportal%"
GROUP BY
temp.target_id
)
它运行,但运行速度非常慢—— 5 分钟,在我写这篇文章时还在数。(我正在运行的子查询NOT IN
返回 36,000 行,我假设父查询需要时间来检查表中的 38,000 个条目中的每一个条目images
与这 36,000 行。)
有没有办法可以加快这个查询?
解决方案
将其写为应该快得多LEFT JOIN
,在 中查找NULL
值user_groups
以指示图像不在该组中:
SELECT i.id
FROM images i
JOIN images_user_groups iu ON iu.images_id = i.id
LEFT JOIN user_groups u ON u.id = iu.user_groups_id AND u.description LIKE "%Freigabe ins Presseportal%"
GROUP BY i.id
HAVING COUNT(u.id) = 0
NOT IN
and的问题NOT EXISTS
是WHERE
必须对images
.
推荐阅读
- sql-server - 当特定列在 SELECT 语句中时查询很慢
- google-chrome - 为什么我的内容安全政策没有得到遵守?
- mongodb - MongoDB 在 $lookup 之后使用 $sort 进行慢聚合
- sql - 使用 SQL 中的 TRIGGER 函数获取插入的前一行/最后一行的数据
- flutter - 如何向 ListView Builder 添加新行
- php - 为什么在启用 gd 时出现“尝试调用函数 imagecreatefrompng”错误?
- javascript - 使用对象键和值设置 html 元素的样式
- tfs - Azure Dev Ops 搜索功能受限于 TFS
- python - 按字符串中的负值对文件中的行进行排序
- python - 在 Python 中使用循环从 XML 文件中提取字符串