Users表有两列,Id和Name PurchasedCars表有4列,LicensePlate,所有者ID,卖方ID和不相关的售价。
例如,我得到了这个数据 用户数 (1,乔希) (2,乔纳森) (3,或) (4,雅各布)
汽车 (123,无关数据) (456,无关数据) (789,无关数据)
已购买的汽车 (123,2,1,50k) (456、3、1、80k) (789,4,1,30k)
输出 (123,乔纳森·乔什) (456,或乔希) (789,Jacob,Josh)
我有三个表,第一个表是用户表,第二个表是售车表,所有者和卖方都是用户ID的外键,我需要将每个人的名字都输入相同的记录集。
,查询的返回将是LicensePlate,所有者名称,工人名称
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
答案 0 :(得分:1)
针对用户加入两次,一次针对所有者,一次针对卖方
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
答案 1 :(得分:0)
我认为您需要的是将Users
和PurchasedCars
两次连接,每个名称一次:
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;