When building a SelectQuery, why can't I use the alias from addExpression() in a condition()? I'm trying to search for nodes with field values that satisfy a mathematical formula. I can build a SelectQuery that will find all nodes and return the value of the computation for each result using addExpression(), but I cannot seem to accomplish the final step of only returning the correct nodes using condition().

Here is a simplified example:

$myquery = db_select('node', 'n');

// Use innerJoin() since node field values are stored in separate tables
$myquery-&gt;innerJoin('field_data_field_number_one', 'one', 'n.nid = one.entity_id');
$myquery-&gt;innerJoin('field_data_field_number_two', 'two', 'n.nid = two.entity_id');

// Add basic node fields and the two value fields so they will be available in the results
$myquery-&gt;fields('n');
$myquery-&gt;addField('one', 'field_number_one_value', 'one');
$myquery-&gt;addField('two', 'field_number_two_value', 'two');

// Add the computation using addExpression()
// In this example the computation has been reduced to a simple sum
$myquery-&gt;addExpression('(one.field_number_one_value + two.field_number_two_value)', 'sumcalc');

// Only return nodes of type desired_type
$myquery-&gt;condition('n.type', 'desired_type');

// The query will execute properly without the following line
$myquery-&gt;condition('sumcalc', 5, '&lt;');

$prex = $myquery-&gt;preExecute();

if ($prex) {
  $qresult = $myquery-&gt;execute();
  foreach ($qresult as $qrecord) {
    // Without the erroneous condition above, this line will print each result
    // and each result will contain the value of the calculation added via addExpression()
    dpm($qrecord);
  }
}


If I try to execute the code above, I get the following error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sumcalc' in 'where clause'


What am I doing wrong here?
The MySQL you're trying to build is invalid - you can't refer to an expression field in a WHERE clause.

You need a HAVING clause for that, which in Drupal-ese is:

$myquery-&gt;havingCondition('sumcalc', 5, '&lt;');