我有38k行的表,我使用这个查询来比较来自items表的item id和来自posted_domains表的item id。
select * from `items`
where `items`.`source_id` = 2 and `items`.`source_id` is not null
and not exists (select *
from `posted_domains`
where `posted_domains`.`item_id` = `items`.`id` and `domain_id` = 1)
order by `item_created_at` asc limit 1该查询采用了8s。我不知道我的查询是否有问题,或者我的mysql配置不好。此查询由Laravel关系生成,如
$items->doesntHave('posted', 'and', function ($q) use ($domain) {
$q->where('domain_id', $domain->id);
});发布于 2016-05-17 16:43:01
相关子查询可能相当慢(因为它们经常被重复执行,对外部查询中的每一行执行一次),这可能会更快。
select *
from `items`
where `items`.`source_id` = 2
and `items`.`source_id` is not null
and item_id not in (
select DISTINCT item_id
from `posted_domains`
where `domain_id` = 1)
order by `item_created_at` asc
limit 1我说可能是因为在where中的子查询在MySQL中也比较慢。
这个左加入可能是最快的。
select *
from `items`
LEFT JOIN (
select DISTINCT item_id
from `posted_domains`
where `domain_id` = 1) AS subQ
ON items.item_id = subQ.item_id
where `items`.`source_id` = 2
and `items`.`source_id` is not null
and subQ.item_id is null
order by `item_created_at` asc
limit 1;因为它是一个不匹配的场景,技术上它甚至不需要是子查询;并且作为一个直接的左联接可能更快,但这将取决于索引,可能还取决于实际的数据值。
https://stackoverflow.com/questions/37281866
复制相似问题