Is there some way to have a formula that is in both the select and where condition only be calculated once?
I assume mysql must do the calculation twice for each row it the following example.
SELECT z1.id sid1,z2.id sid2,SQRT(POW(ABS(z1.col-z2.col),2) + POW(ABS(z1.row-z2.row),2)) r
FROM stars z1,stars z2
WHERE z1.id!=z2.id
AND SQRT(POW(ABS(z1.col-z2.col),2) + POW(ABS(z1.row-z2.row),2)) <=32
ORDER BY z1.id,z2.id
You cannot refer to aliases defined in a
SELECTclause in aWHEREclause, but you can use them in aHAVINGclause. This is becauseWHEREis evaluated beforeSELECTasSELECTmay contain aggregate functions.Beware, though, that the
HAVINGclause will most likely not be used in indexes. You could provide an approximate term to theWHEREclause for indexing purposes:Note that the bottleneck is disk access, not arithmetic calculation, so if you are optimising for speed, you may want to stay with WHERE and only optimise the WHERE clause:
note that
Try: