2017-07-13 84 views
1

我想使用查詢內部的計算來選擇我的結果,並使用這些結果在WHERE語句內部進行比較。但不知何故,這是行不通的。猜你知道爲什麼?這裏是我的代碼:MySQL計算結果在WHERE子句中

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

幫助會很好。感謝那!

+0

例如 「不工作」 怎麼了?它會給出錯誤嗎?沒有,沒有發生?它整天躺在牀上看電視嗎?無論如何,這是行不通的:你需要在where子句中重複相同的表達式,或者把它放在一個帶有別名的子查詢或者CTE中,然後根據你的'select' /'where'關閉這個表達式。 (免責聲明:我不知道MySQL是否支持CTE。) –

+0

[在MySQL查詢的WHERE子句中使用列別名會產生錯誤]的副本(https://stackoverflow.com/questions/942571/using-column-alias- in-where-clause-of-mysql-query-produce-an-error) –

+0

https://stackoverflow.com/questions/2905292/where-vs-having – abigperson

回答

2

您可以使用具有對計算列過濾:

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

清除這裏

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