mysql 查询一个表的序列号,MySQL查询中的每一行都需要一个序列号

So I found this great use:

SELECT (@row:=@row+1) AS ROW, ID

FROM TableA ,(SELECT @row := 0) r

ORDER BY ID DESC

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

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

WHERE ID<500

,(SELECT @row := 0) r

ORDER BY ID DESC

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). The first example works great but for some reaosn, the JOINs mess it up somehow.

so I get this:

ROW | ID

3 15

2 10

1 2

What I am after is:

ROW | ID

1 15

2 10

3 2

Here's the

So 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.

How can I achieve that?

解决方案

Remove the ORDER BY:

SELECT (@row:=@row+1) AS ROW, ID

FROM table1 ,(SELECT @row := 0) r

Then if you want to use an ORDER BY wrap the query in another SELECT:

select *

from

(

SELECT (@row:=@row+1) AS ROW, ID

FROM table1 ,(SELECT @row := 0) r

) x

order by row

Or if you leave the ORDER BY on the query, then you can see the way the row number is being applied by simply playing with either DESC or ASC order - See Demo

If you use DESC order

SELECT (@row:=@row+1) AS ROW, ID

FROM table1, (SELECT @row := 0) r

order by id desc;

the results are which appears to be the result you want:

ROW | ID

----------

1 | 15

2 | 10

3 | 2

If you use ASC order:

SELECT (@row:=@row+1) AS ROW, ID

FROM table1 ,(SELECT @row := 0) r

ORDER BY ID;

the results are:

ROW | ID

----------

1 | 2

2 | 10

3 | 15

Edit, based on your change, you should place the row number in a sub-query, then join the other tables:

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值