I need to select the most recent 2 rows by unix timestamp. I would also like to count the number of occurrences of an ip address. Can I do this with one query?
Here is what my desired end result would look like:
19 12345690 127.0.0.1 2
19 12345678 127.0.0.1 1
Here is what I have so far but it will only return 1 row. I need 2.
SELECT
count(timestamp) numOfOccurances,
timestamp,
ip,
id
FROM x
WHERE ip = '127.0.0.1'
ORDER BY
timestamp DESC
LIMIT 2
Aggregate functions like count() are affected by the LIMIT clause so there’s really no practical way to get a count() (or equivalent) of all matching rows in a table and a LIMITed number of rows at the same time.
If your database server is on the same continent as your application, it will probably be quicker to just run two separate queries.
Edit: By “practical” above I mean there are options using subqueries. If you really, absolutely must have it in one shot…