sqlmysql

mysql calculation results in WHERE clause


I would like to select my results using calculations inside the query and use these results to compare inside the WHERE statement. But somehow that does not work. Guess you know why? Here is my code:

$statement = $pdo->prepare("SELECT * ,  `ft_lteam` -  `ht_lteam` AS  `ht2_lteam`,  
`ft_vteam` -  `ht_vteam` AS  `ht2_vteam` 
FROM  `sca` 
WHERE `ht2_lteam` > `ht2_vteam`");
$statement->execute(array('Max'));

Help would be great. Thanks for that!


Solution

  • You can use HAVING to filter on a computed column:

    $statement = $pdo->prepare("SELECT * ,  `ft_lteam` -  `ht_lteam` AS  `ht2_lteam`,  
    `ft_vteam` -  `ht_vteam` AS  `ht2_vteam` 
    FROM  `sca` 
    HAVING `ht2_lteam` > `ht2_vteam`");
    $statement->execute(array('Max'));
    

    Clear example here

    SELECT col1,col2,col3,(col1*col2*col3) AS result, number FROM table
    HAVING result > number
    ORDER by result