Skip to content
Advertisement

how can I join multiple columns on two table in sql

I have two table like below

create table test_user (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name varchar(64)
);

create table test_info(
        id INT AUTO_INCREMENT PRIMARY KEY,
        sellerId INT,
        buyerId INT,
        x varchar,
        y varchar,
        z varchar
);

how can I get all the information in table test_info and the name of the buyer AND the name of seller from the test_user table in the same statement?

select * from test_table join test_user on sellerId = test_user.id;
or 
select * from test_table join test_user on buyerId = test_user.id;

would just give me a seller or buyer but i would like to get the result for both

Advertisement

Answer

You must join 2 copies of test_user to test_info:

SELECT ti.*, s.name seller_name, b.name buyer_name
FROM test_info ti
INNER JOIN test_user s ON ti.sellerId = s.id
INNER JOIN test_user b ON ti.buyerId = b.id;

The 1st copy of test_user is used to return the seller’s name and the 2nd to return the buyer’s name.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement