简体   繁体   中英

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

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

You seem to want to return all the rows in links_table plus additional rows in pages_table that are not in that table. I would just use union all :

select l.url, l.links
from links_table l
union all
select p.url, null
from pages_table p
where not exists (select 1 from links_table where l.url = p.url);

something like this: (not 100% sure though)

SELECT * 
FROM links_table l 
LEFT OUTER JOIN pages_table p ON p.url = l.url 
UNION 
SELECT * 
FROM links_table l 
RIGHT OUTER JOIN pages_table p ON p.url = l.url 
WHERE l.url IS NULL; 

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