2016-01-20 118 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