MySQL中BETWEEN的正确语法

时间:2013-11-29 03:24:00

标签: mysql between

$SQL="SELECT First_Name, Last_Name, Team, Pos, GP, G, A, (G+A) AS Points FROM stats ORDER BY Points DESC BETWEEN '$b1' AND '$b2'";

给我一​​个syntax error 'near 'BETWEEN '19' AND '17'' at line 1'

1917只是用户输入以替换$b1$b2的变量(在此之间以及此之间等)

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您不能在WHERE子句中使用字段别名。您可以做的是在WHERE子句中再次使用您的作业,如下所示:

SELECT 
    First_Name, 
    Last_Name, 
    Team, 
    Pos, GP, G, A, 
    (G+A) AS Points 
FROM stats 
WHERE 
    (G+A) BETWEEN '$b1' AND '$b2'
ORDER BY Points DESC
  

标准SQL不允许您引用WHERE子句中的列别名。强制执行此限制是因为执行WHERE代码时,可能尚未确定列值。

MySQL文档:http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

答案 1 :(得分:1)

MySQL documentation描述了BETWEEN

的语法
expr BETWEEN min AND max

If expr is greater than or equal to min and expr is less than or equal to max, 
BETWEEN returns 1, otherwise it returns 0

您的案例有两个问题:

  1. BETWEEN将始终返回0,因为19> 17。
  2. 如果没有更多上下文,很难说,但我认为在您的情况下,您希望将BETWEEN用作WHERE子句的一部分。例如,WHERE Points BETWEEN 17 AND 19