我正在运行这样的查询:
SELECT DISTINCT `tableA`.`field1`,
`tableA`.`filed2` AS field2Alias,
`tableA`.`field3`,
`tableB`.`field4` AS field4Alias,
`tableA`.`field6` AS field6Alias
FROM (`tableC`)
RIGHT JOIN `tableA` ON `tableC`.`idfield` = `tableA`.`idfield`
JOIN `tableB` ON `tableB`.`idfield` = `tableA`.`idfield`
AND tableA.field2 IN
(SELECT field2
FROM tableA
GROUP BY tableA. HAVING count(*)>1)
ORDER BY tableA.field2
这是为了找到所有重复的条目,但现在它需要花费大量的时间来执行。有任何优化建议吗?
答案 0 :(得分:3)
您似乎正试图在field2
TableA
上查找所有重复项。第一步是将in
子查询移动到from
子句:
SELECT DISTINCT a.`field1`, a.`filed2` AS field2Alias,
a.`field3`, b.`field4` AS field4Alias, a.`field6` AS field6Alias
FROM tableA a left join
tableC c
on c.`idfield` = a`.`idfield` join
`tableB` b
ON b.`idfield` = a.`idfield` join
(SELECT field2
FROM tableA
group by field2
having count(*) > 1
) asum
on asum.field2 = a.field2
ORDER BY tableA.field2
可能还有其他优化措施,但很难说。你的问题“找到重复”和你的查询“加入一堆表并过滤它们”并不完全匹配。了解哪些表具有哪些索引和唯一/主键也很有用。