【问题标题】:SQL Queries take up longer than 1 hourSQL 查询占用超过 1 小时
【发布时间】:2014-08-27 11:39:45
【问题描述】:

我们的一些 SQL 查询需要超过 3 小时才能执行,考虑到我们的数据库目前大约有 5000 个条目,这确实很长。

这是最长的两条语句:

/* Alte Jobs anzeigen */

update vwr_synch.listings set vwr_synch.listings.Alt="alt"
where vwr_synch.listings.JobKey not in (select vwr_synch.jobs.JobKey from vwr_synch.jobs)
;

update vwr_synch.listings set vwr_synch.listings.Alt="alt" where vwr_synch.listings.VWRStatus="NoJobs" or vwr_synch.listings.VWRStatus="Problem"
;


update vwr_synch.listings set vwr_synch.listings.Alt=NULL 
where vwr_synch.listings.VWRStatus="Active" and vwr_synch.listings.VWRRetry!="0" and vwr_synch.listings.Alt="alt"
;


/* Neue Jobs anzeigen */

update vwr_synch.jobs set vwr_synch.jobs.NeuAlt="Neu"
where vwr_synch.jobs.JobKey not in (select vwr_synch.listings.JobKey from vwr_synch.listings) and (vwr_synch.jobs.`Status`="Active" and vwr_synch.jobs.Retry="0")
;

【问题讨论】:

  • 您正在更新哪些视图? vwr 前缀是干什么用的?
  • @Donal 否 vwr 前缀是由应用程序创建的

标签: mysql sql xampp


【解决方案1】:

您的示例代码有多个语句,所以我只关注第一个。

我更喜欢not in,因为使用NULL 的语义,尽管有证据表明not in 可能更有效(参见cmets 中的链接)。这是第一个查询:

update vwr_synch.listings
    set vwr_synch.listings.Alt = 'alt'
    where vwr_synch.listings.JobKey not in (select vwr_synch.jobs.JobKey from vwr_synch.jobs);

我会改成:

update vwr_synch.listings l
    set l.Alt = 'alt'
    where not exists (select 1 from vwr_synch.jobs.JobKey jk where jk.JobKey = l.JobKey);

然后,为了有效地工作,您需要在vwr_synch.jobs.JobKey(JobKey) 上建立索引。

接下来的两条语句是:

update vwr_synch.listings l
    set l.Alt = 'alt'
     where l.VWRStatus in ('NoJobs', 'Problem');

update vwr_synch.listings l
    set l.Alt = NULL 
    where l.VWRStatus = 'Active' and l.VWRRetry <> '0' and l.Alt = 'alt';

对于这些,您需要vwr_synch.listings(VWRStatus, Alt, VWRRetry) 上的索引。

【讨论】:

  • 根据this articleNOT EXISTS 实际上比NOT IN 慢.. 我会把索引作为你答案的主旨。
  • 另外,使用 where 子句来确定您需要哪些索引。查看您的 sql,我看到这些列上需要索引:vwr_synch.listings.JobKey、vwr_synch.jobs.JobKey、vwr_synch.listings.VWRStatus、vwr_synch.listings.VWRRetry、vwr_synch.listings.Alt、vwr_synch.jobs.Status、vwr_synch。工作。重试
  • @Arth 。 . .我实际上更喜欢NOT IN,因为语义更符合人们的期望。当子查询中的元素之一为假时,NOT IN 永远不会返回真。我修改了答案,但我对博客中的这条评论感到担忧:“很难说出确切的原因......”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 2021-07-07
  • 2013-04-05
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多