![](/img/trans.png)
[英]Subtract two fields in two different tables to insert different into a third field in second table
[英]MYSQL: Joining two different fields to same field in third table
我试图将两个不同的字段连接到第三个查找表中的同一字段。 我的数据结构如下:
Investments table:
Investment_ID
Company_Country_Code (e.g., US, UK, AU, FR)
Fund_Country_Code (e.g., US, UK, AU, FR)
Country Lookup Table:
Country_Code (e.g., US, UK, AU, FR)
Country_Name (e.g., United States, United Kingdom, Australia, France)
我想将Company_Country_Code和Fund_Country_Code都加入到国家/地区查找表中的Country_Code表中,并拉出相应的Country_Names。 我想要这样的数据输出:
(Investment_ID, Company_Country_Name, Fund_Country_Name)
1, United States, France
2, United Kingdom, Australia
3, France, United States
是否有一种特殊的联接来完成此任务?
谢谢!
这完全取决于您想要的内容...如果要过滤掉两个表中都不存在的结果,则使用INNER JOIN ..如果要不过滤而加入,则使用LEFT JOIN
SELECT i.Investment_ID, i.Company_Country_Name, i1.Fund_Country_Name
FROM country_lookup cl
JOIN investments i ON i.Company_Country_Code = cl.Country_Code
JOIN investments i1 ON i1.Fund_Country_Code = cl.Country_Code
无需过滤数据,您可以像这样使用左联接
SELECT i.Investment_ID, i.Company_Country_Name, i1.Fund_Country_Name
FROM country_lookup cl
LEFT JOIN investments i ON i.Company_Country_Code = cl.Country_Code
LEFT JOIN investments i1 ON i1.Fund_Country_Code = cl.Country_Code
没什么特别的-只需进行两个联接:
SELECT
i.Investment_ID,
c.Country_Name as Company_Country_Name,
f.Country_Name as Fund_Country_Name
FROM
Investments i
JOIN
Country c ON i.Company_Country_Code = c.Country_Code
JOIN
Country f ON i.Fund_Country_Code = f.Country_Code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.