如何生成选择查询的记录索引?

时间:2018-03-12 11:58:55

标签: mysql

在将我的问题标记为重复之前,请注意我的情况非常不同。

SELECT
 c.id
 c.date_added AS date_added,
 @INDEX := @INDEX + 1 AS row_index
FROM
 cases c
JOIN (SELECT @INDEX := 0) indexer
LEFT JOIN users u ON c.owner_id = u.id
INNER JOIN case_profiles cases_id ON c.id = cases_id.cases_id

WHERE
 cases_id.`name` LIKE '%case%'
ORDER BY
 c.date_added DESC

它向后生成我的row_index 3,2,1而不是预期的1,2,3,只有当我在JOIN表的列中添加任何条件时才会发生这种情况,例如cases_id。{COLUMN}。

请帮助我克服这个问题 提前谢谢!

1 个答案:

答案 0 :(得分:0)

由于排序,它与您的查询一样;数据在排序之前首先加入。试试这个:

SELECT A.*, @INDEX := @INDEX + 1 AS row_index
FROM
(SELECT
 c.id
 c.date_added AS date_added
FROM
 cases c
LEFT JOIN users u ON c.owner_id = u.id
INNER JOIN case_profiles cases_id ON c.id = cases_id.cases_id
WHERE
 cases_id.`name` LIKE '%case%'
ORDER BY
 c.date_added DESC) A JOIN (SELECT @INDEX := 0) indexer;

请参阅MySQL row_number, This Is How You Emulate It