[英]Unable to get two fields in mysql select query
I have four fields in my route
table 我的route
表中有四个字段
busid, routid, position and distance
I want to show busid and distance from a select query
. 我想显示busid and distance from a select query
。 My select query is as follow : 我的选择查询如下:
$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());
but when I use this query then it gives error : unknown field distance in field list
. 但是当我使用此查询时,它将给出错误: unknown field distance in field list
。 Plese help what I am missing 请帮助我所缺少的
You should not use subqueries in the from
clause, unless necessary in MySQL. 除非在MySQL中是必需的,否则不应在from
子句中使用子查询。 They prevent the optimizer from generating the best query plan. 它们使优化器无法生成最佳查询计划。
A better way to write the query: 编写查询的更好方法:
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;
Your specific problem, of course, is that a.distance
is not defined because it was not defined in the subquery. 当然,您的特定问题是a.distance
因为它未在子查询中定义。
Missing distance in sub-query a 子查询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
Even a better version: 甚至更好的版本:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.