2

I have the following query and I need to add "and distance < 10" to the where clause. Because 'distance' is computed variable it can't be used in where clause. I have tried HAVING instead of where but that breaks the replace part.

I think the answer is to use a temporary table for the distance computation but i can't figure out the syntax as everything I have tried doesn't work.

All help appreciated please. Thanks.

select
    Contractor.contractorID,
    Contractor.firstName,
    Contractor.lastName,
    Contractor.emailAddress,
    Contractor.nationality,
    Contractor.dateOfBirth,
    Contractor.address1,
    Contractor.address2,
    Contractor.city,
    Contractor.county,
    Contractor.postcode,
    Contractor.country,
    Contractor.tel,
    Contractor.mob,
    postcodes.Grid_N Grid_N1,
    postcodes.Grid_E Grid_E1,
    (select Grid_N from postcodes where pCode='".$postcode."') Grid_N2,
    (select Grid_E from postcodes where pCode='".$postcode."') Grid_E2,
    ( (select sqrt(((Grid_N1-Grid_N2)*(Grid_N1-Grid_N2))+((Grid_E1-Grid_E2)*(Grid_E1-Grid_E2))) ))/1000*0.621371192 as distance
from 
    Contractor,
    postcodes 
where 
    postcodes.Pcode = replace(substring(Contractor.postcode,1,length(Contractor.postcode)-3),'','') 
order by 
    distance asc
4

2 回答 2

4

在 MySQL 中,您可以这样做:

where . . .
having distance < 10
order by distance;

您不需要将其他条件放在having子句中。此外,您的查询可以受益于使用 ANSI 标准连接语法(on例如,使用子句)。

于 2013-09-17T15:47:01.487 回答
0
SELECT list
     , of
     , columns
     , including
     , distance
FROM   (
        <your existing query>
        /* minus ORDER BY clause (needs to be on outermost query */
       ) As a_subquery
WHERE  distance < 10
ORDER
    BY some_stuff
于 2013-09-17T15:49:46.967 回答