0

Possible Duplicate:
Need a sequence number for every row in MySQL query

So I found this great use:

SELECT (@row:=@row+1) AS ROW, ID  
FROM TableA ,(SELECT @row := 0) r   
ORDER BY ID DESC

My tables look more like this:

SELECT (@row:=@row+1) AS ROW, ID , ColA, ColB, ColC
FROM TableA 
JOIN TableB on TableB.ID = TableA.ID
JOIN TableC on TableC.ID = TableA.ID 
,(SELECT @row := 0) r   
ORDER BY ID DESC

The @row:=@row+1 works great, but I get the row ordered by the ID.

so I get something more like this:

ROW  | ID  
3      15  
2      10  
1      2

What I am after is:

ROW  | ID  
1      15  
2      10  
3      2

Note: I noticed that if I remove the JOINs I DO get the requested result (In Which ROW is the sequential number of each row, no matter the ORDER BY of ID)

It basically seems that the row number is evaluated before the ORDER BY takes place. I need the ORDER BY to take place after row was given.

Any idea regarding how I can achieve that, and what do the JOINS do that messes it up?

Thx!

Community
  • 1
  • 1
Ted
  • 3,805
  • 14
  • 56
  • 98

1 Answers1

0

I need the ORDER BY to take place after row was given.

Then try this:

SELECT *
FROM
(
   SELECT (@row:=@row+1) AS ROW, ID , ColA, ColB, ColC
    FROM TableA 
    JOIN TableB on TableB.ID = TableA.ID
    JOIN TableC on TableC.ID = TableA.ID 
    ,(SELECT @row := 0) r 
) t
ORDER BY ROW ASC
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164