1

My tests give the same run rate. I'm trying to figure out that it's best to use join or subquery. I understand that much depends on the data, the indexes, and the DB itself, but I want to distinguish it so if the records in t1 are less than t2 then the subquery should be effective, but if on the contrary then join.

EXPLAIN ANALYSE SELECT *
FROM safety_policies
WHERE safety_policies.area_id IN (SELECT areas.id
                                  FROM areas
                                    INNER JOIN departments ON areas.department_id = departments.id);


EXPLAIN ANALYSE SELECT safety_policies.*
                FROM safety_policies
                  INNER JOIN areas ON safety_policies.area_id = areas.id
                  INNER JOIN departments ON areas.department_id = departments.id;
4
  • it will have two identical results Apr 29, 2018 at 12:43
  • Fundamentally, unless there is a SIGNIFICANT performance difference (and there shouldn't be) you should be guided by whichever most accurately reflects your intent. The code readabiity is important and this will be largely informed by the intent in the construction of the query.
    – Alan
    Apr 29, 2018 at 12:50
  • 1
    @YaroslavMaluk . . . The two queries may happen to produce the same results because of your data, but they are not guaranteed to. Hence, you should express the query that implements your intent: do you or do you now want duplicates from safety_policies depending on what is in the other two tables. Apr 29, 2018 at 13:02
  • I realized why you replied about duplication - no logic would allow me to have duplication. I'm just very confused - I can do it in different ways, but I do not know what's better Apr 29, 2018 at 13:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy