Question

$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'";

Giving me a syntax error 'near 'BETWEEN '19' AND '17'' at line 1'

(19 and 17 are just variables a user inputs to replace $b1 and $b2 (between this and between this, etc)

Any suggestions?

Was it helpful?

Solution

You can't use a field alias in that WHERE clause. What you can do is use your assignment again in the WHERE clause like this:

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

Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

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

OTHER TIPS

The MySQL documentation describes the syntax of 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

There are two problems in your case:

  1. BETWEEN will always return 0, since 19 > 17.
  2. It's hard to say without more context, but I think in your case, you want to use BETWEEN as part of a WHERE clause. For example, WHERE Points BETWEEN 17 AND 19
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top