2013-09-25 48 views
-1

當我嘗試執行下面的sql時,收到一條錯誤消息,指出無效的列名距離。我沒有在我的sql中發佈過那麼多,所以我不確定這個isue是什麼。先謝謝您的幫助!SQL中存在的問題具有子句

SELECT ID, 
    3959 * ACOS(COS(RADIANS(34.743305)) 
    * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
    + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance 
FROM RetailerRegistration 
HAVING (distance < 25) 
+1

有時,列別名可用的上下文取決於DBMS。你的代碼[在MySQL中工作正常](http://sqlfiddle.com/#!2/d1021/6)。你需要澄清你的DBMS是什麼。 PostgreSQL的?甲骨文? SQL Server? SQLlite? –

回答

0

havinggroup by一起使用。我認爲你有它與where ...混淆...此外,請嘗試將公式放入where子句中,而不是引用別名。

SELECT ID, 
    3959 * ACOS(COS(RADIANS(34.743305)) 
    * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
    + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance 
FROM RetailerRegistration 
WHERE 
    3959 * ACOS(COS(RADIANS(34.743305))  
    * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586))  
    + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) < 25 
-1

你不使用任何一組由..trying做這樣的:

SELECT ID, 3959 * ACOS(COS(RADIANS(34.743305)) * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance FROM RetailerRegistration where (distance < 25) 

HAVING子句來強加行不是個別行

希望這有助於集團condidtion。 ...

+0

它仍然認爲列名距離與where子句無效。 – user2815584

+0

'HAVING'子句至少適用於MySQL中的單個行。 – Minoru

5

的問題是,你正試圖引用您在SELECT列表中創建一個別名,我建議使用子查詢,然後使用您的別名:

select ID, distance 
from 
(
    SELECT ID, 
    3959 * ACOS(COS(RADIANS(34.743305)) 
     * COS(RADIANS(Lattitude)) * COS(RADIANS(Longitude) - RADIANS(- 85.059586)) 
     + SIN(RADIANS(34.743305)) * SIN(RADIANS(Lattitude))) AS distance 
    FROM RetailerRegistration 
) d 
where distance < 25; 

的邏輯順序處理查詢是:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. 選擇
  6. ORDER BY

結果別名distance尚未被定義爲您的WHERE子句。解決這個問題的一種方法是使用子查詢。

+4

對,在FROM,WHERE,GROUP BY和HAVING子句執行之後,SELECT列表的內容不會(邏輯地)創建,因此它們的列別名還不存在,因此您不能在這些子句中引用它們。 – RBarryYoung