MySQL在同一列上连接相同的表两次,不同的值仅返回最近的行

时间:2013-06-23 06:07:09

标签: mysql join

我试图解决一小部分复杂的JOIN问题。

我们有一个'说明'表和'估计'表。在'估计'中,对于给定的指令,我们为不同类型的estimates提供了多行。

说明表

id | address | status
1 | 27 TAYLOR ROAD, ALBION PARK NSW 2527 | InProgress

估算表

id | instruction_id | basis | basis_date | basis_value
1 | 1 | ContractPrice | 2012-04-05 | 124000
2 | 1 | CAMV | 2012-02-01 | 120000
3 | 1 | CustomerEstimate | 2012-06-07 | 132000
4 | 1 | ContractPrice | 2013-01-03 | 140000
5 | 1 | CustomerEstimate | 2013-02-09 | 145000

我们想要的实际上是基于instructions.id = estimate.instruction_id和estimate.basis对'估计'的2个连接加入1)最近的'CustomerEstimate'(别名basis_date和basis_value为estimate_date和estimate_value) 2)最近的'ContractPrice'(再次,将basis_date和basis_value别名为contact_date和contract_value)。

预期结果如下;

id | address | status | contract_price | contract_date | estimate_date | estimate_value
1 | 27 TAYLOR ROAD, ALBION PARK NSW 2527 | InProgress | 2013-01-03 | 140000 | 2013-02-09 | 145000

我非常感谢那些SQL大师的帮助。

非常感谢, 遄。

2 个答案:

答案 0 :(得分:1)

尝试

SELECT i.id,  
       i.address, 
       i.status,
       p.max_date contract_date, 
       p.basis_value contract_price, 
       e.max_date estimate_date, 
       e.basis_value estimate_value
  FROM Instructions i LEFT JOIN
(
    SELECT q1.instruction_id, max_date, basis_value
      FROM Estimates e JOIN
    (
        SELECT instruction_id, MAX(basis_date) max_date
          FROM Estimates
         WHERE basis = 'CustomerEstimate'
         GROUP BY instruction_id
    ) q1 ON e.instruction_id = q1.instruction_id AND e.basis_date = q1.max_date
) e ON i.id = e.instruction_id LEFT JOIN
(
    SELECT q2.instruction_id, max_date, basis_value
      FROM Estimates e JOIN
    (
        SELECT instruction_id, MAX(basis_date) max_date
          FROM Estimates
         WHERE basis = 'ContractPrice'
         GROUP BY instruction_id
    ) q2 ON e.instruction_id = q2.instruction_id AND e.basis_date = q2.max_date
) p ON i.id = p.instruction_id

输出:

| ID |                              ADDRESS |     STATUS | CONTRACT_PRICE | CONTRACT_DATE | ESTIMATE_VALUE | ESTIMATE_DATE |
----------------------------------------------------------------------------------------------------------------------------
|  1 | 27 TAYLOR ROAD, ALBION PARK NSW 2527 | InProgress |         140000 |    2013-01-03 |         145000 |    2013-02-09 |

这是 SQLFiddle 演示。

答案 1 :(得分:0)

这里的contract_price是什么? 您可以尝试以下

select inst.id
     , inst.address
     , inst.status
     , est.basis_value as estimate_value
     , est.basis_date as estimate_date 
  from instructions inst
     , estimates est 
 where inst.id=est.instruction_id 
   and (est.basis='CustomerEstimate' or est.basis='ContractPrice') 
 order 
    by est.basis
     , est.basis_date desc;