2016-01-20 89 views
0

兩個領域我已經在我的route表四個字段無法獲得MySQL中選擇查詢

busid, routid, position and distance

我想顯示busid and distance from a select query。我選擇的查詢是如下:

$endb = mysql_query("select case when a.position < b.position then a.busid when a.position > b.position then a.busid else null end as busid, a.distance as distance from (select busid,position from route where routid=$result2) a join (select busid,position from route where routid=$end) b on a.busid = b.busid") or die(mysql_error()); 

但是當我使用這個查詢然後提示錯誤:unknown field distance in field list。普萊舍幫助我錯過了什麼

子查詢
+1

distane!=距離 –

+0

我在場地列表中有距離 –

+0

哦,好的。 (我沒有downvoted順便說一句) –

回答

1

失蹤距離

select 
    case 
     when a.position < b.position then a.busid 
     when a.position > b.position then a.busid 
     else null 
    end as busid, 
    a.distance as distance 
from (
    select busid, position, distance 
    from route 
    where routid=$result2 
) as a join (
    select busid, position 
    from route 
    where routid=$end 
) as b 
on a.busid = b.busid 

即使是一個更好的版本:

SELECT if (a.position <> b.position, a.busid, null) busid, a.distance 
FROM route a, route b 
WHERE a.busid = b.busid 
AND a.routid= $result2 
AND b.routid= $end 
+0

關鍵字AS是可選的,不需要。可能是上面提到的錯字。 – Niagaradad

+0

是關鍵字AS是可選的 – SIDU

+0

對於閱讀此內容的任何人:雖然解決方案在技術上是正確的,但這不是編寫查詢的最佳方式。 MySQL實現了子查詢,導致開銷並阻止索引的使用進一步處理。 –

4

你不應該在MySQL中from子句中使用子查詢,除非必要。它們阻止優化器生成最佳查詢計劃。

一種更好的方式來編寫查詢:

select (case when a.position < b.position then a.busid 
      when a.position > b.position then a.busid 
     end) as busid, 
     a.distance 
from route a join 
    route b 
    on a.busid = b.busid and 
     a.routid = $result2 and b.routid = $end; 

您的特定問題,當然,是a.distance沒有定義,因爲它沒有在子查詢中定義。

+0

是的,這個答案比較好 – SIDU

+0

+1。 CASE表達式可以通過單個不等式比較'WHEN a.position <> b.position'進一步簡化。 – spencer7593