Reputation: 49
While executing below query facing "Lost connection to MySQL server during query" error. 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
Upvotes: 1
Views: 107
Reputation: 1269583
You can speed up not in
subqueries in older versions by MySQL by replacing them with not exists
. The appropriate indexes definitely help (as recommended by Steven Moseley.
This version moves the joins into the from
clause and replaces the not in
with 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. 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.
Upvotes: 1
Reputation: 16325
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)
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, e.g.
ALTER TABLE firmalar ADD INDEX (firmaID);
ALTER TABLE musterisahipleri ADD INDEX (firmaID);
ALTER TABLE musterisahipleri ADD INDEX (userID);
ALTER TABLE notlar ADD INDEX (ilgiliID);
Upvotes: 5