I got mysql query like this:
SELECT name,
(SELECT timePing
FROM TerminalPings
WHERE terminalsId = Terminals.id
ORDER BY timePing DESC LIMIT 1)
as timePing
FROM Terminals`
It works good, but i need to select top 2 timePing’s from TerminalPings, and name them like timePing1 and timePing2. What is the best way to do it?
EDIT:
opps, sorry guys, but there actually is a relation between TerminalPings and Terminals… my bad 🙁 I feel so stupid about forgetting to write WHERE statement 🙁
2nd UPDATE:
Deriving @OMG Ponies’ solution for the updated question:
New test case:
New result:
EXPLAIN output (MySQL 5.1.45)
UPDATE: @OMG Ponies’ solution is faster than the one I suggested earlier (see the comments to both answers for reasons). I’m leaving the answer here for reference (this answer still returns a correct result, just much slower when you have many rows in the outer query: in the terminals table).
I would still stuggest using two separate queries. While SQL is a very expressive language, there’s no need to do everything in one query… just like there’s no need to do a task in a single line of code in other programming languages! The fact that MySQL made the subqueries in the solution below uncachable is one form of potential problems that you may face when using complicated queries (which may easily be broken down into two or more very simply queries).
Previous Answer:
You may want to use two separate queries instead. But just for the challenge, you may want to try the following:
Test case:
Result:
EXPLAIN output (MySQL 5.1.45) (see the comments for @OMG Ponies’ answer):