我想优化以下MySql查询,它从2个表中挑选数据,其中authorchecklist表具有详细记录,而selectedrevlist表用于评论者的评论。
我想从selectedrevlist获取那些记录,其中scoreSubmit = 1
SELECT *
FROM `authorchecklist` acl
WHERE acl.manuscriptStatus = 'Awaiting Reviewer Assignment'
AND acl.submitStatus = '1'
AND
( SELECT COUNT( 1 )
FROM selectedrevlist srl
WHERE srl.OrderNumber = acl.OrderNumber
AND srl.editorType = 'Editor'
AND srl.editorID = '10'
AND srl.scoreSubmit = '1'
) = 1
以上查询工作正常,但加载记录需要大约20秒。 如果有人可以帮助我优化查询,请提前感谢
答案 0 :(得分:1)
这是您的查询:
SELECT acl.*
FROM authorchecklist acl
WHERE acl.manuscriptStatus = 'Awaiting Reviewer Assignment' AND
acl.submitStatus = 1 AND
(SELECT COUNT(1)
FROM selectedrevlist srl
WHERE srl.OrderNumber = acl.OrderNumber AND
srl.editorType = 'Editor' AND
srl.editorID = 10 AND
srl.scoreSubmit = 1
) = 1 ;
对于此查询,您需要authorchecklist(submitStatus, manuscriptStatus, OrderNumber)
和selectedrevlist(OrderNumber, editorId, scoreSubmit)
上的索引。
答案 1 :(得分:0)
我重新安排了查询以便于阅读:
SELECT *
FROM `authorchecklist` acl
WHERE acl.manuscriptStatus = 'Awaiting Reviewer Assignment'
AND acl.submitStatus = '1'
AND (
SELECT COUNT( 1 )
FROM selectedrevlist srl
WHERE srl.OrderNumber = acl.OrderNumber
AND srl.editorType = 'Editor'
AND srl.editorID = '10' AND srl.scoreSubmit = '1'
) = 1
我假设每个作者检查清单中只有一个选定的列表。
您没有发送表定义(" CREATE TABLE ..."),但可能至少有一个字段没有编入索引:
authorchecklist.manuscriptStatus
selectedrevlist.OrderNumber
如果他们没有编入索引,SQL服务器将需要横向所有记录。它将横向所有authorchecklist行,并且对于每个authorchecklist行,它将横穿所有selectedrevlist行以找到" srl.OrderNumber = acl.OrderNumber"。索引可能会使插入速度变慢,但如果它们被正确使用,它们会加快读数。
[删除了错误的断言]
如果您正在使用MySQL,请添加" LIMIT 1"当您确定始终只会获取一条记录时。此外,使用InnoDB引擎并添加外键 - 这些是验证关系的索引。
看看这些:
答案 2 :(得分:0)
添加以下索引:
ALTER TABLE
`authorchecklist`
ADD
INDEX `authorchecklist_idx_manuscriptstatu_submitstatus` (`manuscriptStatus`, `submitStatus`);
ALTER TABLE
`authorchecklist`
ADD
INDEX `authorchecklist_idx_ordernumber` (`OrderNumber`);
ALTER TABLE
`selectedrevlist`
ADD
INDEX `selectedrevlist_idx_editort_editori_scoresu_ordernu` (
`editorType`,
`editorID`,
`scoreSubmit`,
`OrderNumber`
);
使用EXISTS代替计数记录的子查询。 存在子查询将在找到某些内容后退出,而不是计算与过滤器匹配的所有行。
SELECT
*
FROM
`authorchecklist` acl
WHERE
acl.manuscriptStatus = 'Awaiting Reviewer Assignment'
AND acl.submitStatus = '1'
AND EXISTS (SELECT *
FROM
selectedrevlist srl
WHERE
srl.OrderNumber = acl.OrderNumber
AND srl.editorType = 'Editor'
AND srl.editorID = '10'
AND srl.scoreSubmit = '1')