复合连接1结果2相同连接

时间:2013-12-28 15:33:32

标签: mysql join

我有一张包含一些预订的表格。预订有业主和接收人。两者都是数字并且对应于他们的帐户ID。但现在我想从另一个表中检索他们的名字。我可以JOIN 1个名字,但我怎么能加入另一个名字?

    SELECT 
       firstName AS receiverName,
       carName, 
       ownerId, 
       receiverId, 
FROM   system_bookings 
       INNER JOIN link_car_user 
               ON system_bookings.carLinkId = link_car_user.id 
       INNER JOIN system_cars
               ON llink_car_user.carId = system_cars.id 
       INNER JOIN system_users 
               ON system_bookings.receiverId = system_users.id 

WHERE  ownerId = '1' 
        OR receiverId = '1' 

您可以看到使用了多个表。现在这给出了以下结果:

ReceiverName | carName | ownerId | receiverId

Peter        | Toyota  | 1       |     12   
Walter       | Ford    | 13      |     1

但我想添加ownerName。哪个也可以通过system_users表检索。

如何在单个查询中执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以再次使用ownerId上的system_users表加入,如下所示:

SELECT receiver.firstName AS receiverName,
    owner.firstName AS ownerName,
    carName, 
    ownerId, 
    receiverId
FROM system_bookings 
INNER JOIN link_car_user 
    ON system_bookings.carLinkId = link_car_user.id 
INNER JOIN system_cars
    ON llink_car_user.carId = system_cars.id 
INNER JOIN system_users receiver
    ON system_bookings.receiverId = receiver.id 
INNER JOIN system_users owner
    ON system_bookings.ownerId = owner.id 
WHERE  ownerId = '1' 
    OR receiverId = '1'