我的route表中有四个字段

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。请帮助我所缺少的

最佳答案

子查询a中缺少距离

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

10-07 13:28