如何获取行数(记录ID所在的位置)

时间:2015-05-14 11:54:23

标签: mysql

这是分期付款表。我希望得到的是instalments.id 46站在第3排。

请务必查看订单号。

第一列是结果应该返回的值。

     |  id  | order_id |
------------------------
  1  |  23  | OOO12345 |
------------------------
  2  |  45  | OOO12345 |
------------------------
  3  |  46  | OOO12345 |
------------------------
  4  |  61  | OOO12345 |

------------------------
  1  |  62  | OOO12346 |
------------------------
  2  |  63  | OOO12346 |
------------------------
  3  |  64  | OOO12346 |
------------------------

instalments.id = 46  =>  3 
instalments.id = 63  =>  2


SELECT  wr.order_id, i1.previous_rows
        // other fields from other joined tables
FROM writers.work_records wr
LEFT JOIN writers.instalments i ON i.id = wr.instalment_id
LEFT JOIN (
     SELECT COUNT(id) as previous_rows, order_id, id
     FROM instalments
) AS i1 ON i1.order_id = wr.order_id AND i1.id <= wr.instalment_id
WHERE 
    wr.order_id = '00012345'
    conditions

请帮助。

2 个答案:

答案 0 :(得分:1)

假设您的ID有序,您可以选择ID低于或等于您想要的ID的行数:

SELECT COUNT(id) as previous_rows
FROM installments 
WHERE id <= 46

答案 1 :(得分:0)

SQL:

SET @rownum = 0;

SELECT id
FROM
  (SELECT id
   FROM instalments
   WHERE id = 46) rownum;

OR

SELECT id
FROM
  (SELECT id
   FROM instalments,
     (SELECT @rownum:=0) r) rownum
WHERE id = 46