![](/img/trans.png)
[英]MySQL join for two tables based on on column and excluding the values of another column
[英]How do I join two tables on one column while preserving the values in another column?
我有两张桌子。
链接表
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
在 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
您似乎想要返回links_table
所有行以及pages_table
中不在该表中的其他行。 我只会使用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);
像这样:(虽然不是 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.