简体   繁体   English

如何在保留另一列中的值的同时连接一列上的两个表?

[英]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 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?如何以保留链接数量的方式组合所有 URL?

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:在 MySQL 中,您可以使用UNION ALL和聚合模拟full join

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.您似乎想要返回links_table所有行以及pages_table中不在该表中的其他行。 I would just use union all :我只会使用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)像这样:(虽然不是 100% 确定)

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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