如何将一列INNER JOIN到两个不同的列?

时间:2019-03-07 13:15:20

标签: mysql inner-join

我有两个表:

**projects**

|Equity_holders| Financer  |
|--------------|-----------|
|Company 1     | Company 7 |
|Company 2     | Company 9 |
|Company 3     | Company 4 |

**entities**

|name         | country |
|-------------|---------|
|Company 1    |  USA    |
|Company 2    |  Italy  |
|Company 3    |  UK     |
|Company 4    |  Nigeria|
|Company 5    |  Brazil |
|Company 6    |  China  |
|Company 7    |  France |
|Company 8    |  China  |
|Company 9    |  Germany|

我希望我的显示表如下所示:

|Equity_holders| country |Financer     | country |
|--------------|---------|-------------|---------|
|Company 1     |  USA    |Company 4    |  Nigeria|
|Company 2     |  Italy  |Company 7    |  France |
|Company 3     |  UK     |Company 9    |  Germany|                       

我已经成功地使用INNER JOIN来将“股权持有人”列与实体名称进行匹配,并显示相应的“国家/地区”:

SELECT projects.Equity_holders,entities.country, projects.Financer,entities.country
FROM projects
INNER JOIN entities ON projects.Equity_holders LIKE CONCAT('%', entities.name, '%')
INNER JOIN entities A ON projects.Financer LIKE CONCAT('%', entities.name, '%' )

但是无法获得“财务”列来显示正确的相应国家/地区。它只是复制“ Equity_Holders”列。我觉得选择查询有问题,但无法确定要更改的内容。

2 个答案:

答案 0 :(得分:1)

您可以在下面尝试-您需要为第二个实体e1加上别名,并将e1.country用作country1

SELECT projects.Equity_holders,entities.country, projects.Financer,e1.country
FROM projects
INNER JOIN entities ON projects.Equity_holders=entities.name
INNER JOIN entities e1 ON projects.Financer=e1.name

答案 1 :(得分:0)

您应该在获得项目后获得A.country。如果您想要融资人所在的国家/地区,请提供财务。

尝试以下操作:

SELECT projects.Equity_holders,entities.country, projects.Financer,A.country
FROM projects
INNER JOIN entities ON projects.Equity_holders LIKE CONCAT('%', entities.name, '%')
INNER JOIN entities A ON projects.Financer LIKE CONCAT('%', entities.name, '%' )