[英]Mysql long execution query
我有38k行的表,並且使用此查詢來比較items表中的項目ID和postd_domains表中的項目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
此查詢用時8秒 。 我不知道我的查詢是否有問題,或者我的mysql配置錯誤。 該查詢由Laravel關系生成,例如
$items->doesntHave('posted', 'and', function ($q) use ($domain) {
$q->where('domain_id', $domain->id);
});
關聯的子查詢可能相當慢(因為它們經常重復執行,對於外部查詢中的每一行都執行一次),因此可能會更快。
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相當慢的子查詢。
這種左聯接可能是最快的。
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;
由於這是一個不匹配的情況,因此從技術上講,它甚至不需要是子查詢。 並且作為直接左聯接可能更快,但這將取決於索引以及可能的實際數據值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.