需要MySQL查询中每一行的序列号

时间:2012-10-03 11:36:14

标签: mysql sql-order-by

所以我觉得这很有用:

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

@row:=@row+1效果很好,但我按照ID排序。

我的表看起来更像是这样:

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 
WHERE ID<500
,(SELECT @row := 0) r   
ORDER BY ID DESC

注意: 我注意到if I remove the JOINs I DO get the requested result(其中ROW是每行的序号,无论ID的ORDER BY如何)。第一个例子效果很好但是对于某些原因,JOIN会以某种方式弄乱它。

所以我明白了:

ROW  | ID  
3      15  
2      10  
1      2

我所追求的是:

ROW  | ID  
1      15  
2      10  
3      2

这是 SqlFiddle

因此,基本上似乎在ORDER BY发生之前评估行号。我需要在给出行之后进行ORDER BY

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:8)

删除ORDER BY

SELECT (@row:=@row+1) AS ROW, ID  
FROM table1 ,(SELECT @row := 0) r   

请参阅SQL Fiddle with Demo

然后,如果您想使用ORDER BY将查询包装在另一个SELECT中:

select *
from 
(
  SELECT (@row:=@row+1) AS ROW, ID  
  FROM table1 ,(SELECT @row := 0) r
) x
order by row

或者如果您将ORDER BY留在查询上,那么只需使用DESCASC订单 - {{3即可看到行号的应用方式}}

如果您使用DESC订单

SELECT (@row:=@row+1) AS ROW, ID  
FROM table1, (SELECT @row := 0) r
order by id desc;

结果似乎是您想要的结果:

ROW | ID
----------
1   | 15
2   | 10
3   | 2

如果您使用ASC订单:

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

结果是:

ROW | ID
----------
1   | 2
2   | 10
3   | 15

编辑,根据您的更改,您应该将行号放在子查询中,然后加入其他表:

select *
from
(
  SELECT (@row:=@row+1) AS ROW, ID  
  FROM Table1,(SELECT @row := 0) r   
  order by ID desc
) x
JOIN Table2 
  on x.ID = Table2.ID;

请参阅See Demo

答案 1 :(得分:2)

我发现您的查询没有任何问题

SELECT (@row:=@row+1) AS ROW, ID  
FROM table1 ,(SELECT @row := 0) r   
order by ID desc


SQL Fiddle demo