簡體   English   中英

非常慢的SQL語句

[英]Very slow SQL statement

我在使用SQL語句時遇到一些重大問題,以下語句對MySQL引擎造成了很大壓力,幾乎掛起了:

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate
from explorer.booking_record br1
inner join explorer.client c
on c.labelno = br1.labelno
and email not like ''
where br1.bookingdate >= '2009-01-01'
and br1.bookingdate < '2009-01-31'
and c.labelno Not In (Select labelno from explorer.booking_record br2 where br2.labelno = br1.labelno and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31')

我嘗試了相同的幾種變體,沒有聯接和兩個子語句,按照文檔的建議添加了“ order by”。 數據庫中實際上沒有多少記錄,booking_record有約500,000條記錄,客戶有約450,000。 如果我讓查詢運行,通常在70-80秒后會得到大約20個結果,但這會使服務進入類似循環的狀態。

任何建議將不勝感激。

丹尼爾。

不喜歡和不喜歡是這里的罪魁禍首。

將“ NOT LIKE更改為<> 由於您沒有使用任何通配符,因此您在這里不需要任何“喜歡”行為,因此您只需將其更改為“不相等”運算符即可。

緊接着,您是否已經查看了執行計划並調查了是否在可以使用索引的列上創建了索引?

您是否已將索引放在where字段上? 不在且不喜歡被稱為緩慢,因此也許您可以避免這種說法。

確保索引以下各列:

explorer.booking_record.labelno
explorer.booking_record.bookingdate
explorer.booking_record.labelno
explorer.client.labelno
explorer.client.email

現在嘗試以下查詢:

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate
from explorer.booking_record br1
left outer join explorer.booking_record br2 on br2.labelno = br1.labelno
    and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31'
inner join explorer.client c on c.labelno = br1.labelno and c.email <> ''
where br1.bookingdate >= '2009-01-01'
    and br1.bookingdate < '2009-01-31'
    and br2.labelno is null

“不參加”的過程往往很慢。 嘗試類似這樣的操作,確保在兩個表中都對labelno進行了索引。

select c.title, c.initial, c.surname, c.labelno, c.email, br1.bookingdate 
from explorer.booking_record br1
inner join explorer.client c
on c.labelno = br1.labelno
and email not like ''
where br1.bookingdate >= '2009-01-01'
and br1.bookingdate < '2009-01-31'
and Not Exists (Select 1 from explorer.booking_record br2 where br2.labelno = br1.labelno and br2.bookingdate >= '2010-01-01' and br2.bookingdate < '2010-01-31')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM