Mysql长执行查询

时间:2016-05-17 16:35:16

标签: mysql sql database performance laravel-5.2

我有38k行的表,我使用此查询来比较items表中的item id和来自posting_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);
});

1 个答案:

答案 0 :(得分:0)

CORRELATED子查询可能相当慢(因为它们经常重复执行,外部查询中的每一行一次),此可能更快。

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

我说可能因为MySQL中的子查询也相当慢。

此LEFT JOIN可能是最快的。

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;

由于它是无匹配场景,因此技术上甚至不需要是子查询;并且作为直接左连接可能更快,但这将取决于索引以及可能的实际数据值。

相关问题