MySQL JOIN查询帮助:连接具有按降序排序的不同右表行的两个表

时间:2014-02-10 07:29:43

标签: mysql sql join

我有两张桌子,一张用于投诉,另一张用于指派技术人员

表1: - complaints

------------------------------------------
| id | complaint      | charges | status |
------------------------------------------
| 1  | gas kit broken | 250     |  2     |
| 2  | water leakage  | 100     |  2     |
| 3  | too much smoke | 150     |  2     |
------------------------------------------

现在,对于1次投诉,许多技术人员可以一个接一个地分配,直到投诉得到解决,所以

表2: - assign

------------------------------------------------
| id | complaint_id | technician | assign_date |
------------------------------------------------
| 1  | 1            | 24         | 1391904000  |
| 2  | 1            | 55         | 1391598500  |*
| 3  | 2            | 20         | 1391600000  |
| 4  | 2            | 31         | 1391676500  |
| 5  | 2            | 25         | 1391665000  |*
| 6  | 3            | 26         | 1391682000  |
| 7  | 3            | 28         | 1391800000  |*
------------------------------------------------

我想要的是将状态= 1的所有投诉行加入到complaints的最后一行分配.id = assign。complaint_id。

我用星号(*)标记了它们,所以输出就是

-----------------------------------------------------------------------------------------
| id | complaint      | charges | status | id | complaint_id | technician | assign_date |
-----------------------------------------------------------------------------------------
| 1  | gas kit broken | 250     |  2     | 2  | 1            | 55         | 1391598500  |
| 2  | water leakage  | 100     |  2     | 5  | 2            | 25         | 1391665000  |
| 3  | too much smoke | 150     |  2     | 7  | 3            | 28         | 1391800000  |
-----------------------------------------------------------------------------------------

我的工作平台是: - PHP和MySQL

1 个答案:

答案 0 :(得分:1)

select a.*, b.*
from complaint as a left join
    (select c.*
     from assign as c
     where c.id in (
        select max(d.id) as max_id
        from assign as d
        group by complaint_id)) as b
        on a.id = b.complaint_id