Kousha
Kousha

Reputation: 36189

MySQL join on the latest row

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.

Upvotes: 1

Views: 4803

Answers (1)

Barmar
Barmar

Reputation: 780724

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

Upvotes: 1

Related Questions