执行以下查询时面临“在查询期间丢失与MySQL服务器的连接”错误。 我该如何解决?
SELECT *
FROM firmalar,
musterisahipleri,
notlar
WHERE firmalar.firmaID NOT IN (
SELECT m2.firmaID
FROM notlar AS n2,
musterisahipleri AS m2
WHERE n2.eklemeTarihi > '2013-03-24'
)
AND musterisahipleri.firmaID = firmalar.firmaID
AND notlar.ilgiliID = musterisahipleri.userID;
感谢您的帮助
答案 0 :(得分:5)
你正在超时,因为你正在使用效率低下的嵌套子查询。
这样做会更好:
编辑:根据您的上一条评论,此查询将返回自“2013-03-24”以来未添加firmalar
条记录的notlar
条记录...然后将这些结果加入{{1} 1}}和musterisahipleri
再次获取相关的代表和备注(如果适用)
notlar
您还应该确保在您加入的列上有索引,例如
SELECT *
FROM (
SELECT f.*
FROM firmalar AS f
LEFT JOIN musterisahipleri AS m
ON m.firmaID = f.firmaID
LEFT JOIN notlar AS n
ON n.ilgiliID = m.userID
AND n.eklemeTarihi > '2013-03-24'
GROUP BY f.firmaID
HAVING MAX(n.ilgiliID) IS NULL
) AS f
LEFT JOIN musterisahipleri AS m
ON m.firmaID = f.firmaID
LEFT JOIN notlar AS n
ON n.ilgiliID = m.userID
答案 1 :(得分:1)
您可以通过将not in
替换为not exists
来加速旧版本的from
子查询。适当的指数肯定有帮助(正如Steven Moseley所建议的那样。
此版本将联接移动到not in
子句中,并将not exists
替换为SELECT *
FROM firmalar join
musterisahipleri
on musterisahipleri.firmaID = firmalar.firmaID join
notlar
on notlar.ilgiliID = musterisahipleri.userID
WHERE not exists (select 1
FROM notlar n2 join
musterisahipleri m2
on n2.ilgiliID = m3.userID
WHERE n2.eklemeTarihi > '2013-03-24' and
firmalar.firmaID = m2.firmaID
)
:
not in
在编写本文时,我意识到原始查询的问题是join
子查询中的表未正确连接在一起。这再次强调了为什么正确的连接语法(使用on
子句中的from
和where
关键字)优于{{1}}子句中的隐式连接。