我的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
。请帮助我缺少的东西
答案 0 :(得分: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
未定义,因为它未在子查询中定义。
答案 1 :(得分: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