0

Tables...

contracts
---------
id

contract_locations
------------------
id
contract_id     # A contract can have many contract locations.
name            # E.g., "Front office", "Legal", "Contracts admin", etc.
arrival_date

Users consider the location with the last arrival_date to be a given contract's "current location".

They want to be able to find all contracts with a current location name equal to (for example) "Front office" or "Legal".

How can I write a MySQL 5.1 query to do that?

4

2 回答 2

1

这是一种方法:

select c.id
from (select c.*,
             (select name
              from contract_locations cl
              where cl.contract_id = c.id
              order by arrival_date desc
              limit 1
             ) CurrentLocation
      from contracts c
     ) c
where CurrentLocation = 'Front Office'

这使用相关子查询来获取当前位置。通过在Contract_Locations(contract_id, arrival_date).

这是另一种可能不太明显的方法。这个想法是查看最近的日期是否是给定位置的最近日期。这使用了一个having子句:

select contract_id
from contract_locations cl
group by contract_id
having max(arrival_date) = max(case when name = 'Front Office' then arrival_date end)

该子句仅在(或其他)是最近日期having时才成立。'Front Office'

于 2013-06-06T23:04:58.827 回答
1
SELECT contract_id
FROM contract_locations l
JOIN (SELECT contract_id, MAX(arrival_date) curdate
      FROM contract_locations
      GROUP BY contract_id) m
ON l.contract_id = m.contract_id and l.arrival_date = m.curdate
WHERE l.name = 'Front Office'
于 2013-06-06T23:28:45.993 回答