我有以下查询,我需要在where子句中添加“和距离< 10”。因为'distance'是计算变量,所以不能在where子句中使用。我已经尝试过HAVING而不是那里,但是打破了替换部分。
我认为答案是使用临时表进行距离计算,但我无法弄清楚语法,因为我尝试的所有内容都不起作用。
所有帮助表示赞赏。感谢。
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
答案 0 :(得分:4)
在MySQL中,你可以这样做:
where . . .
having distance < 10
order by distance;
您不需要将其他条件放在having
子句中。此外,您的查询可以从使用ANSI标准连接语法(例如,使用on
子句)中受益。
答案 1 :(得分: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