0
SELECT *
FROM table_a 
LEFT JOIN table_b ON (table_b.id = table_a.id) 
WHERE table_b.created BETWEEN ? AND ? 
      AND table_b.manager IN(
        SELECT DISTINCT (b.id) 
        FROM table_b a 
          INNER JOIN table_b b ON a.manager = b.id 
            AND b.user_level > 0
            AND b.id != 1
      )

How can I remove the sub query and use JOINS instead in the above query

Thanks

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
Saranya
  • 3
  • 3

1 Answers1

0

MySQL 5.5 (and lower version)'s optimizer produces a DEPENDENT SUBQUERY for IN (SELECT ...) which means every matching row is found, IN(SELECT ...) is evaluated that makes select slow.

Simple optimization of your query is make inline view as follows:

SELECT *
FROM table_a LEFT JOIN table_b ON (table_b.id = table_a.id) 
    INNER JOIN (
            SELECT DISTINCT b.id AS id
            FROM table_b a 
              INNER JOIN table_b b ON a.manager = b.id 
                AND b.user_level > 0
                AND b.id != 1
    ) x ON table_b.manager = x.id
WHERE table_b.created BETWEEN ? AND ? 
  AND x.id IS NOT NULL;

I think avobe query would produce as same as your own.

Last, DISTINCT is not a function. please use SELECT DISTINCT b.id rather SELECT DISTINCT (b.id)

Community
  • 1
  • 1
Jason Heo
  • 9,956
  • 2
  • 36
  • 64