简体   繁体   中英

SQL get multiple values (from the same column from same table) from table with 2 foreign keys to the first table

Users Table has two columns, Id And Name PurchasedCars Table has 4 columns, LicensePlate, Owner's Id, Seller's Id, and selling price that isn't relevant.

For an example i got this data Users (1, Josh) (2, Jonathan) (3, Or) (4, Jacob)

Cars (123, irrelevant data) (456, irrelevant data) (789, irrelevant data)

PurchasedCars (123, 2, 1, 50k) (456, 3, 1, 80k) (789, 4, 1, 30k)

Output (123, Jonathan, Josh) (456, Or, Josh) (789, Jacob, Josh)

I got three tables the first table is a table of users and the second table is a table of sold cars both the owner and seller are foreign keys to Id in users and i need to get the name of each of them to the same record set.

and the return of the query would be LicensePlate, Owner's name, Worker's name

SQL CODE

Select Cars.LicensePlate From Cars
Union 
Select Users.Name as WorkerName From Users, PurchasedCars 
Where Users.Id=PurchasedCars.Seller
Union
Select Users.Name as BuyerName From Users, PurchasedCars 
Where Users.Id=PurchasedCars.Owner

Join twice against users, once for owner and once for seller

SELECT p.licensePlate, u1.name as 'Workers name', u2.name as 'Sellers name'
FROM PurchacedCars p
JOIN Users u1 ON p.seller = u1.id
JOIN Users u2 ON p.owner = u2.id

I think what you need here is to just join Users to PurchasedCars twice, once for each name:

SELECT
    pc.LicensePlate,
    u1.Name AS worker_name,
    u2.Name AS owner_name
FROM PurchasedCars pc
INNER JOIN Users u1
    ON pc.Seller = u1.Id
INNER JOIN Users u2
    ON pc.Owner = u2.Id;

在此处输入图片说明

Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM