MySQL join on the latest row

亡梦爱人 提交于 2021-01-28 05:39:38

问题


I have two tables agents and calls. An agent will always be on one active call. There can be another pending call assigned to an agent that an agent has not yet answered.

I want to write a single query that tests to see if the latest call as sorted by dateCreated matches the call that is currently active in the agent`s table.

Here is an example where the active call matches the agent's call: http://sqlfiddle.com/#!9/af5bd/5

Here is an example where the active call does not match the agent's call: http://sqlfiddle.com/#!9/70b7e0/8

The query I am running is

# 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;

The first query will always return 1, but the second query works. I'm not a big fan of writing a second query inside my query. Is there a way around this?

Update Maybe this was not clear, but I basically want to see if the latest entry in the calls table matches the callId from the agents table.


回答1:


Join the agents table with a subquery that returns the most recent call ID:

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


来源:https://stackoverflow.com/questions/44291451/mysql-join-on-the-latest-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!