Search code examples
mysqlsqlleft-joinunionfull-outer-join

How do I join two tables on one column while preserving the values in another column?


I have two tables.

links_table

URL                     Links
example.com/1           6
example.com/2           2
example.com/3           4

pages_table

URL
example.com/2
example.com/4

How do I combine all the URLs in a way that preserves the number of links?

Desired result:

URL                     Links
example.com/1           6
example.com/2           2
example.com/3           4
example.com/4           null

Solution

  • In MySQL, you can emulate a full join with UNION ALL and aggregation:

    select url, max(links) links
    from (
        select url, links from links_table
        union all
        select url, null from pages_table
    ) t
    group by url