首页 > 解决方案 > 如何在一个列上连接两个表,同时保留另一列中的值?

问题描述

我有两张桌子。

链接表

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

pages_table

URL
example.com/2
example.com/4

如何以保留链接数量的方式组合所有 URL?

期望的结果:

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

标签: mysqlsqlleft-joinunionfull-outer-join

解决方案


在 MySQL 中,您可以模拟full joinwithUNION ALL和聚合:

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

推荐阅读