我尝试此查询以获取所选行中的行号,但输出类似于23,56,78,....我需要获得1,2,3到每个选定的行。请帮帮我
SET @row=0;
SELECT `table1`.`col1`,`table1`.`col2`,@row:=@row+1
FROM `table1`
LEFT OUTER JOIN `table2` ON `table1`.`col1` = `table2`.`col5`
WHERE `table2`.`col5` IS NOT NULL
GROUP BY `col1` ORDER BY `table1`.`col7` DESC LIMIT 0,10
答案 0 :(得分:4)
将带有ORDER BY
子句的查询移动到子查询中。
SET @row = 0;
SELECT col1, col2, @row := @row+1
FROM (SELECT table1.col1, table1.col2
FROM table1
LEFT JOIN table2 ON table1.col1 = table2.col5
WHERE table2.col5 IS NOT NULL
GROUP BY col1
ORDER BY table1.col7 DESC
LIMIT 0, 10) AS subquery
答案 1 :(得分:1)
您可以尝试使用内嵌视图。使用获取要返回的行的查询,然后将其包装在parens中,并在外部查询的FROM
子句中引用该查询。
这样的事情:
SELECT v.`col1`
, v.`col2`
, @row := @row + 1 AS `rn`
FROM ( SELECT `table1`.`col1`
, `table1`.`col2`
FROM `table1`
...
ORDER BY ...
LIMIT 10
) v