我有两张表agents
和calls
。代理将始终处于一个活动呼叫中。可以有另一个未决呼叫分配给代理尚未应答的代理。
我想编写一个查询来测试,以查看按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
匹配。
答案 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