![](/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.