merging two SELECT queries

后端 未结 2 1152
南笙
南笙 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.

    0 讨论(0)
  • 2021-02-10 04:20

    I'd probably use a UNION.

    SELECT `date`
       FROM `tasks` WHERE `user_id`=1
    UNION
    SELECT `t1`.`date`
       FROM `tasks` `t1`
       INNER JOIN `urls` `u1` ON `u1`.`id` = `t1`.`url_id`
       WHERE `u1`.user_id`=1;
    
    0 讨论(0)
提交回复
热议问题