Tech Blog
from
Full TechBlog List
<< previous entries
Search:
next entries >>

AIDS (1)  |  BIOS (1)  |  drive letter (1)  |  drivers (1)  |  Flash (19)  |  Google Maps (1)  |  hard drive (5)  |  hardware (3)  |  IDE/PATA (0)  |  Javascript (3)  |  memory (1)  |  motherboard (3)  |  MySQL (1)  |  networking (1)  |  optimization (6)  |  PHP (2)  |  RAM (1)  |  ribanc (4)  |  SATA (1)  |  SEO (0)  |  software (2)  |  software installation (1)  |  spyware (1)  |  trojan (1)  |  virus (1)  |  webprogramming (23)  |  Windows Vista (1)  |  Windows XP (6)  |  XP Antivirus (1)

Richárd Nagy 'Kapa'
programmer
 
Ordinal row numbers in MySQL queries
2008.10.28.

One day I just ran into the problem that in a MySQL query I want to give an ordinal row number to every resulting record. So I wanted a result something like:

  1. Mocskarc
  2. Retkarc
  3. Kecsege

In a MySQL SELECT statement, you can use variables. You do this by putting a @ before the variable name (like @zsiguli). You can assign values using := like in good old Pascal. So my first version was something like this:

select @a:=@a+1 as rownum, name from sometable ...

For the first look, this seems allright, but using counters (@a) without initialization is not a good idea. So you can either run another command before this (@a:=0), which is not nice enough, or you can use a small trick. Subqueries in a SELECT are of course executed before the whole SELECT itself. So let's do this:

select @a:=@a+1 as rownum, name from (select @a:=0) as whatever, sometable ...

Enjoy.


Home