Search code examples
mysqlinner-join

How to INNER JOIN one column to two different columns?


I have two tables:

**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|

I want my display table to look like:

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

I've successfully used INNER JOIN to match the 'Equity holder' column with Entities name and display the corresponding 'country':

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, '%' )

But can't get the 'Financer' column to display the right corresponding country. It just duplicates the 'Equity_Holders' column. I have a feeling its a problem with the select query but can't figure what to change.


Solution

  • You can try below - you need to alias your 2nd entities e1 and use e1.country as 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