我在查询中添加了OR条件,查询执行时间从不到0.5秒到达15+秒。在where子句中使用的所有列都已编制索引。想知道如何优化此查询。
SELECT SQL_NO_CACHE COUNT(DISTINCT wo.id) AS totrows
FROM wo
LEFT JOIN wu
ON wu.id = wo.id
LEFT JOIN bu
ON bu.id = wu.id
LEFT JOIN ub
ON ub.uid = bu.id
JOIN u
ON u.id = wo.created_by
LEFT JOIN ws
ON ws.wo_id = wo.id, b
WHERE (wo.bid = '13'
AND (wo.created_by IN('2506') OR wo.uid IN('2506') )
AND wo.status != 5
AND ( wo.uid = '' || wu.uid in ( '406', 0) || wo.uid IS NULL )
AND wo.ut = 0
AND ( (wo.wt = 'unit' AND (wo.archive != 1 OR wo.archive IS NULL) ) OR wo.wt = 'common' )) OR (ws.uid = 2506 )
删除OR (ws.uid = 2506 )
会使查询速度非常快。
答案 0 :(得分:0)
我最终使用了这样的SELECT COUNT(*) FROM (Query1 union Query2)
。到目前为止看起来不错。
SELECT COUNT(*) AS totrows FROM (
SELECT SQL_NO_CACHE COUNT(DISTINCT wo.id) AS totrows
FROM wo
LEFT JOIN wu
ON wu.id = wo.id
LEFT JOIN bu
ON bu.id = wu.id
LEFT JOIN ub
ON ub.uid = bu.id
JOIN u
ON u.id = wo.created_by
LEFT JOIN ws
ON ws.wo_id = wo.id
WHERE (wo.bid = '13'
AND (wo.created_by IN('2506') OR wo.uid IN('2506') )
AND wo.status != 5
AND ( wo.uid = '' || wu.uid in ( '406', 0) || wo.uid IS NULL )
AND wo.ut = 0
AND ( (wo.wt = 'unit' AND (wo.archive != 1 OR wo.archive IS NULL) ) OR wo.wt = 'common' )) OR (ws.uid = 2506 )
UNION
select DISTINCT wo.id from wo LEFT JOIN ws ON ws.wo_id = wo.id WHERE ws.uid = 2506
) AS T