簡體   English   中英

我需要一張臨時桌子嗎?

[英]Do I need a temporary table?

我有以下查詢,我需要在where子句中添加“ and distance <10”。 由於“距離”是計算變量,因此不能在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

在MySQL中,您可以執行以下操作:

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

您無需將其他條件放在having子句中。 同樣,使用ANSI標准聯接語法(例如,使用on子句)可以使查詢受益。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM