左连接或类似查询

时间:2013-04-30 07:23:51

标签: mysql left-join inner-join

我的数据库中有租用架构。

它有3个表,user,rentingTrack和lock。

用户具有独特的RFIDCode元素。 在rentingTrack我可能有用户(他或她至少租了一次)或不(他/她从未租用)。如果用户租用我需要returnLock作为最后一笔租金,因为rentingID是自动增量的,它是max(rentingID)。 使用锁定表我得到了停车ID,我需要的数据。

enter image description here

问题是如何获取parkingID,我有一半查询:

 SELECT  u.userID, l.parkingID

 FROM locks l, user u

LEFT JOIN (SELECT r1.* FROM rentingTrack r1 INNER JOIN 
(SELECT userID, MAX(rentingID) maxRentingID FROM rentingTrack GROUP BY userID) r2 
on r1.rentingID = r2.maxRentingID) r on u.userID = r.userID 

 WHERE u.userCodeRFID= 3166681355

我需要的是,如果userID不在我所获得的rentingTrack表中:

   userID   |  parkingID
  ----------+-----------
        34  |     NULL 

如果userID在rentingTrack中

   userID   |  parkingID
  ----------+-----------
        34  |        5

如何完成查询以获取parkingID?

2 个答案:

答案 0 :(得分:1)

试试这个。 (需要重复的一些示例数据)

select distinct u.userID,l.parkingID
from users
left join rentingTrack r on u.userID=r.userID
left join locks l on r.returnLock=l.lockid

答案 1 :(得分:0)

SELECT  u.userID, l.parkingID

FROM user u

LEFT JOIN (SELECT r1.userID, r1.returnLock
           FROM rentingTrack r1
           INNER JOIN 
              (SELECT userID, MAX(rentingID) maxRentingID
               FROM rentingTrack
               GROUP BY userID) r2 
           ON r1.rentingID = r2.maxRentingID) r on u.userID = r.userID 

LEFT JOIN locks l ON r.returnLock = l.lockID

WHERE u.userCodeRFID= 3166681355