如何在两个表有条件的情况下编写MySQL查询?

时间:2013-06-06 22:59:42

标签: mysql sql

表...

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

用户认为最后arrival_date的位置是给定合约的“当前位置”。

他们希望能够找到当前位置name等于(例如)“前台”或“法律”的所有合约。

如何编写MySQL 5.1查询来执行此操作?

2 个答案:

答案 0 :(得分: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'(或其他)是最近日期时才为真。

答案 1 :(得分: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'
相关问题