简体   繁体   中英

How can I fix this sql query?

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

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, 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM