在 SQL 语句中使用局部变量时出现问题

Problem using a local variable in a SQL statement

我有这个SQL声明:

SELECT DNI, puntaje, @row := @row+1 as Puesto
FROM postulante, (SELECT @row := 0) r
WHERE idCa = 2 
  AND idPer = 1 
  AND @row <= (SELECT vacantes 
                FROM carrera_abierta 
                WHERE idCa=2 AND idPer=1)
ORDER BY puntaje DESC ;

我想限制列值返回的行数。但是当我 运行 时: It doesn't work:

Of course the result of the subquery is a small value:

怎么了?

您需要使用子查询:

SELECT * 
FROM (SELECT DNI, puntaje, @row := @row+1 as Puesto
      FROM postulante, (SELECT @row := 0) r
      WHERE idCa = 2 
        AND idPer = 1 
      ORDER BY puntaje DESC) sub
WHERE Puesto <= (SELECT vacantes 
                FROM carrera_abierta 
                WHERE idCa=2 AND idPer=1)
ORDER BY Puesto;