MySQL加入最新一行

时间:2017-05-31 17:44:16

标签: mysql join

我有两张表agentscalls。代理将始终处于一个活动呼叫中。可以有另一个未决呼叫分配给代理尚未应答的代理。

我想编写一个查询来测试,以查看按dateCreated排序的最新调用是否与代理程序表中当前处于活动状态的调用相匹配。

以下是活动呼叫与座席呼叫匹配的示例:http://sqlfiddle.com/#!9/af5bd/5

以下是活动呼叫与座席呼叫不匹配的示例: http://sqlfiddle.com/#!9/70b7e0/8

我正在运行的查询是

# This does not work
SELECT count(*) from calls c
  INNER JOIN agents a ON a.callId = c.id
ORDER BY c.dateCreated DESC LIMIT 1;

# This works
SELECT count(*) from calls c
  INNER JOIN agents a ON a.callId = (SELECT id FROM calls ORDER BY dateCreated DESC LIMIT 1)
ORDER BY c.dateCreated DESC LIMIT 1;

第一个查询将始终返回1,但第二个查询有效。我不是在我的查询中编写第二个查询的忠实粉丝。有办法解决这个问题吗?

更新 也许这不清楚,但我基本上想看看calls表中的最新条目是否与callId表中的agents匹配。

1 个答案:

答案 0 :(得分:0)

使用返回最新呼叫ID的子查询加入agents表:

SELECT COUNT(*)
FROM agents AS a
JOIN (SELECT id AS latest_call
      FROM calls
      ORDER BY dateCreated DESC
      LIMIT 1) AS c ON a.callid = c.id
WHERE a.id = @agent_you_care_about