merging two SELECT queries

后端 未结 2 1161
南笙
南笙 2021-02-10 03:45

I am either getting old or the queries that I need to write are getting more and more complicated. The following query will get all the tasks associated with the us

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-10 04:15

    You can do this in a single query:

    SELECT t.date
      FROM TASKS t
     WHERE t.user_id = 1
        OR EXISTS(SELECT NULL
                    FROM URLS u
                   WHERE u.id = t.url_id
                     AND u.user_id = 1)
    

    However, OR is a notoriously bad performer -- it splinters the execution plan. Splitting the query, joining the result sets can be done using the UNION or UNION ALL operators. UNION removes duplicates from the final result set; UNION ALL does not remove duplicates and is faster for it.

    SELECT t.date
      FROM TASKS t
     WHERE t.user_id = 1
    UNION ALL
    SELECT t.date
      FROM TASKS t
     WHERE EXISTS(SELECT NULL
                    FROM URLS u
                   WHERE u.id = t.url_id
                     AND u.user_id = 1)
    

    Know your data, so you know which UNION operator best serves your needs.

提交回复
热议问题