Convert Subquery to Self Join Convert Subquery to Self Join sqlite sqlite

Convert Subquery to Self Join


The result you are looking for using a self join is:

SELECT DISTINCT t1.*FROM ma t1JOIN ma t2  ON  t1.SCHEDULED_ID <> t2.SCHEDULED_ID --Satisfies 2nd queryWHERE t2.ACTION_ID = 3 --Satisfies 2nd query    OR  t1.ACTION_ID = 3 --Satisfies 1st queryORDER BY t1.ID


I don’t think a JOIN is really what you need here. I would use the following query, which avoids UNION :

SELECT m.* FROM ma mWHERE     m.action_id = 3    OR NOT EXISTS (        SELECT 1        FROM ma m1        WHERE             m1.scheduled_id = m.scheduled_id            AND m1.action_id = 3    )

When it comes to checking for the existence (or absence) of something, NOT EXISTS with a correlated subquery is usually the most relevant and efficient approach.


SELECT m1.* FROM ma m1INNER JOIN(    SELECT *     FROM ma m2     WHERE m2.action_id = 3) AS matbl WHERE m1.action_id = 3 OR matbl.scheduled_id<>m1.scheduled_id

Hope it will help.