简体   繁体   中英

SQLite simplify union of left outer join

I inherited some monster SQL queries and I would like to simplify/ shorten them as much as possible.

One of them is:

SELECT 
              * 
            FROM 
              (
                SELECT 
                  $columnsFromBothTables
                FROM 
                  table_abc
                  left outer join table_xyz using profile_id 
                union 
                select 
                  $columnsFromBothTables
                from 
                  table_xyz 
                  left outer join table_abc using profile_id
              ) 

It looks weirdly redundant.
Is there a way to simplify it to sth like?

SELECT * FROM (
    SELECT $columns FROM table_abc MAGIC_OPERATION table_xyz
)

Isn't it a FULL OUTER JOIN?

Updates : My understanding is that both tables have M-1 relationship to "profile" table.

They do not have direct relationship to each other

This is similar to but not exactly a full outer join . I would recommend this approach for the full outer join :

select $columns
from abc left join
     xyz
     on . . .
union all
select $columns
from xyz left join
     abc
     on . . .
where abc.? is null;  -- some column to validate that there is no match

Note: This does not remove duplicates -- which your code does. That is why this version should perform better. But it might not do exactly what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM