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
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.
In addition to the other answer, you can also try subquerys on SELECT:
SELECT t.*, (SELECT name FROM test_user WHERE id=t.sellerId) sellerName, (SELECT name FROM test_user WHERE id=t.buyerId) buyerName
FROM test_info t;
In this case, I think this would be less efficient, but it's an useful resource that you can use in the future
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.