[英]How can I fix this sql query?
While executing below query facing "Lost connection to MySQL server during query" error. 在执行下面的查询时遇到“在查询过程中失去与MySQL服务器的连接”错误。 how can I fix it?
我该如何解决?
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;
Thanks for your help 谢谢你的帮助
You're timing out because you're using inefficient nested subqueries. 您之所以超时,是因为您使用的嵌套嵌套查询效率低下。
This will perform better: 这样会更好:
EDIT: Per your last comment, this query will return you firmalar
records that have no notlar
records added since '2013-03-24'... it then joins those results on musterisahipleri
and notlar
again to get associated reps and notes (if applicable) 编辑:根据您最后的评论,这个查询将返回
firmalar
有没有记录notlar
,因为“2013年3月24日”添加的记录......它,然后加入这些结果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
You should also ensure you have indexes on the columns you're joining on, eg 您还应确保要加入的列上有索引,例如
ALTER TABLE firmalar ADD INDEX (firmaID);
ALTER TABLE musterisahipleri ADD INDEX (firmaID);
ALTER TABLE musterisahipleri ADD INDEX (userID);
ALTER TABLE notlar ADD INDEX (ilgiliID);
You can speed up not in
subqueries in older versions by MySQL by replacing them with not exists
. 您可以加快
not in
在老版本的子查询由MySQL通过与替换它们not exists
。 The appropriate indexes definitely help (as recommended by Steven Moseley. 适当的索引肯定有帮助(如Steven Moseley所建议。
This version moves the joins into the from
clause and replaces the not in
with not exists
: 此版本将联接移入
from
子句,并将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
)
In writing this, I realize that the problem with the original query is that the tables in the not in
subquery were not properly joined together. 在撰写本文时,我意识到原始查询的问题在于
not in
子查询中的表未正确连接在一起。 This yet again emphasizes why proper join syntax (using the join
and on
keywords in the from
clause) is superior to implicit joins in the where
clause. 这再次强调了为什么正确的联接语法(在
from
子句中使用join
和on
关键字)优于where
子句中的隐式联接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.