eEcho blog

is een halte van de gedachte

ORDER BY Id DESC LIMIT 1

if that hadn’t worked? Or what if we’re using an older MySQL that doesn’t have subselects yet? Simple. We can rewrite the query as two SELECT statements and store the intermediate value in a variable on the server side so that no client-side state is required:

mysql> SELECT @max := MAX(Id) FROM Headline;

+—————–+

| @max := MAX(Id) |

+—————–+

| 13962322 |

+—————–+

1 row in set (0.00 sec)

mysql> SELECT Url FROM Headline WHERE Id = @max;

+———————————————-+

| Url |

+———————————————-+

| http://biz.yahoo.com/bw/030331/315850_1.html |

+———————————————-+

1 row in set (0.00 sec)

We don’t even need to explain those queries. Based on what we already know, they’ll obviously be fast (and they are). Both are queries on primary keys and fetch single values.

And, for completeness, the most MySQL-like way to write that query is to use an ORDER BY and LIMIT:

SELECT Url FROM Headline ORDER BY Id DESC LIMIT 1;

Comments are closed.

Home | info@eecho.info | Voorwaarden | Blog