选择与MAX相同的行中的列(列)

时间:2012-07-31 16:28:51

标签: mysql sql greatest-n-per-group

好的,这是我的SQL,我正在使用MySQL:

SELECT 
  assets.id,  
  IF(max(asset_checkins.time) IS NULL AND max(asset_checkouts.time) IS NOT NULL, 'checked-out', 
    IF(max(asset_checkouts.time) > max(asset_checkins.time), 'checked-out',  
    'checked-in')
  ) 'status',  
  asset_checkouts.user, asset_checkouts.location  
FROM 
  assets  
  left outer join asset_checkouts on asset_checkouts.asset = assets.id  
  left outer join asset_checkins on asset_checkins.asset = assets.id  
group by assets.id;

问题是user和location列不是来自与该资产的max(psdl_asset_checkouts.time)对应的行。

相反,我得到:

id  status          user    location  
15  checked-out     1       4<-this  
16  checked-out     1       4  

当我想要:

id  status          user    location  
15  checked-out     1       7<-this  
16  checked-out     1       4  

这是asset_checkouts表,我想要的值是“7”;与资产15的最大(时间)对应的值

id      user    asset   time            location  
3       1       15      7/30/12 12:29   4  
14      1       15      7/31/12 11:01   7

我的想法是我需要做一个子选择,但我不确定这样做的最好方法。

1 个答案:

答案 0 :(得分:1)

它不漂亮但它有效。它将返回资产的最新状态以及签出或签入的用户和位置。如果签到和签出位于同一个表中,这可能会更好一些。

SELECT id,`status`,user,location FROM
    (
     SELECT a.id, 'checked-out' `status`,co.`time`, co.user, co.location
     FROM assets a left join asset_checkouts co on a.id=co.asset

     UNION ALL

     SELECT a.id, 'checked-in' `status`, ci.`time`, ci.user, ci.location
     FROM assets a left join asset_checkins ci on a.id=ci.asset
     WHERE NOT ci.`time` IS NULL
    ) U

WHERE `time` = GREATEST((SELECT COALESCE(MAX(`time`),0)
                         FROM asset_checkouts co
                         WHERE co.asset=U.id),
                        (SELECT COALESCE(MAX(`time`),0) 
                         FROM asset_checkins ci
                         WHERE ci.asset=U.id))