mysqlsqlfilteringwhere-clausecolumn-alias

Cannot use alias from SELECT clause in the WHERE clause


USE stormtrooper_java;

SELECT imperial_battlegroup.BGID, imperial_battlegroup.Designation, imperial_battlegroup.HQ_LocationX, imperial_battlegroup.HQ_LocationY,
stormtrooper_unit.STUID, stormtrooper_unit.UnitCmd, stormtrooper_unit.UnitType, stormtrooper_unit.Location_X, stormtrooper_unit.Location_Y,
ABS(stormtrooper_unit.Location_X - stormtrooper_unit.Location_Y) AS XYRange 
from imperial_battlegroup inner join
     stormtrooper_unit
     on imperial_battlegroup.BGID = stormtrooper_unit.UnitCmd
WHERE Designation = 'Battle Group I' and UnitType = 'Aslt Infantry' AND 
      XYRange > 100;

When I execute the file without XYRange > 100 it works very well, but I do need that filtering logic in the query.

How can I adjust my query to filter the results by this calculated condition?


Solution

  • Try this:

    SELECT imperial_battlegroup.BGID, imperial_battlegroup.Designation, 
    imperial_battlegroup.HQ_LocationX, imperial_battlegroup.HQ_LocationY,
    stormtrooper_unit.STUID, stormtrooper_unit.UnitCmd, 
    stormtrooper_unit.UnitType, stormtrooper_unit.Location_X, 
    stormtrooper_unit.Location_Y,
    ABS(stormtrooper_unit.Location_X - stormtrooper_unit.Location_Y) AS XYRange 
    from imperial_battlegroup inner join
    stormtrooper_unit
    on imperial_battlegroup.BGID = stormtrooper_unit.UnitCmd 
    WHERE Designation = 'Battle Group I' and UnitType = 'Aslt Infantry' AND 
    ABS(stormtrooper_unit.Location_X - stormtrooper_unit.Location_Y) > 100;
    

    Just updated the last line, rest everything is same.