MySQL join语句只返回一个联合记录

时间:2015-12-03 11:02:11

标签: mysql join

我有两张桌子:

请求:

+----+------+----+
| id | from | to |
+----+------+----+
|  1 | aaaa | aa |
+----+------+----+
|  2 | aaab | ab |
+----+------+----+
|  3 | aabb | bb |
+----+------+----+

REQUEST_STATUS

+----+--------+---------+---------+
| id | req_id |  status |  time   |
+----+--------+---------+---------+
|  1 |    1   | pending |  mm-dd  |
+----+--------+---------+---------+
|  2 |    1   | sent    |  mm-dd  |
+----+--------+---------+---------+
|  3 |    2   | pending |  mm-dd  |
+----+--------+---------+---------+
|  2 |    2   | failed  |  mm-dd  |
+----+--------+---------+---------+
|  4 |    3   | pending |  mm-dd  |
+----+--------+---------+---------+

在请求表上,我必须记录:中间状态和已完成的请求状态。

我需要的是某种join语句,每个请求只返回一个状态,但只有在失败或发送不存在时才返回挂起状态。

结果:

+----+------+----+---------+
| id | from | to | status  |
+----+------+----+---------+
|  1 | aaaa | aa | sent    |
+----+------+----+---------+
|  2 | aaab | ab | failed  |
+----+------+----+---------+
|  3 | aabb | bb | pending |
+----+------+----+---------+

select r.id, r.from, r.to, s.status  from requests r
join request_status s on r.id = s.req_status
where r.status not like 'pending'

将返回没有待处理状态。

1 个答案:

答案 0 :(得分:0)

您好像正在尝试显示加入request最新对应行的request_status行。

为了使其工作得相当好,您的request_status.id列必须是主键,需要自动增量。也就是说,request_status中的每个新行都必须具有更高的id值。这就是我们如何判断哪一行比另一行更新。

然后,这很容易。此子查询生成最近的id值集。 (http://sqlfiddle.com/#!9/c845b/1/0

        SELECT MAX(id) latest_id
          FROM request_status
         GROUP BY req_id

然后在连接中使用子查询,如下所示(http://sqlfiddle.com/#!9/c845b/3/0

SELECT r.id, r.from, r.to, s.status
  FROM request r
  JOIN request_status s ON r.id = s.req_id
  JOIN (
            SELECT MAX(id) latest_id
              FROM request_status
             GROUP BY req_id
        ) t ON s.id = t.latest_id

第三个JOIN操作基本等同于

 WHERE s.id IN (
        SELECT MAX(id) latest_id
          FROM request_status
         GROUP BY req_id
       )

它会过滤掉每个请求ID的最新状态行。