显示总线名称和总线号的查询,其中总线的来源是另一条总线的目的地,反之亦然

a query to show name of the bus and busno, where source of a bus is the destination of another bus and vice versa

有两个table,一个是Buses,其中提供总线名称和总线no.s,另一个是schedule ,其中公交车 no.s,公交车的来源和公交车的目的地将可用。所以基本上,这里我们需要显示两条总线的名称和编号作为最终输出,其中总线 X 将总线 Y 的目的地作为其源,而总线 Y 将总线 X 的源作为其目的地。由于源和目标在同一个table,我不知道如何形成逻辑。本质上要用于此问题的概念是连接。

类似于此的代码应该可以解决问题:

SELECT buses.name, buses.number
FROM buses JOIN (SELECT sc1.number
                 FROM schedule AS sc1 JOIN schedule AS sc2
                 ON sc1.source = sc2.destination 
                 AND sc1.destination = sc2.source) AS s1
ON buses.number = s1.number

不确定 SQL 你写的语法是什么,但这在逻辑上应该是正确的。

SELECT B.BUS_NO,BUS_NAME FROM BUSES B JOIN (SELECT S.BUS_NO FROM SCHEDULE S JOIN SCHEDULE S1 ON S.SOURCE=S1.DESTINATION 
AND S.DESTINATION=S1.SOURCE) TMP 
ON B.BUS_NO=TMP.BUS_NO;

去掉'as'结果就出来了

   select buses.bus_no,buses.bus_name
    from buses join( select sc1.bus_no
                    from  schedule sc1 join schedule sc2
                    on  sc1.source=sc2.destination
                    and sc1.destination=sc2.source )  s1
                    on buses.bus_no=s1.bus_no ;

这是另一种不用 sub-query

的方法
select b.bus_no, b.bus_name
from buses b, schedule s1, schedule s2
where b.bus_no=s1.bus_no and s1.source=s2.destination
and s2.source=s1.destination and s1.bus_no!=s2.bus_no
order by 1;

select bus_no,bus_name from buses where bus_no in(select sc1.bus_no from schedule sc1,schedule sc2 where sc1.source=sc2.destination and sc1.destination=sc2.source) order by bus_no;

这里我在子查询中使用了自连接概念:
"select sc1.bus_no 来自计划 sc1,计划 sc2 其中 sc1.source=sc2.destination 和 sc1.destination=sc2.source".
此子查询将 return 来自计划 table 的所有 bus_no 其源与目标相同,最后主查询将 return 对应 bus_no 和 bus_name 来自总线 table,其 bus_no 匹配 bus_no return 的列表 return 通过子查询。

select b.bus_no, b.bus_name,s1.source,s1.destination
from buses b, schedule s1, schedule s2
where b.bus_no=s1.bus_no and s1.source=s2.destination
and s2.source=s1.destination and s1.bus_no!=s2.bus_no
order by bus_no;

这是另一种方法没有连接:

select bus_no,bus_name from buses where bus_no in (
    select s1.bus_no from schedule s1,schedule s2 
    where s1.source=s2.destination and s1.destination=s2.source
)
order by bus_no;

易于理解且有效 100%

select 不同于公交车 buses.bus_no、buses.bus_name 其中 buses.bus_no in(select s1.bus_no 来自时间表 s1 在 s1.source=s2.destination 和 s2.source = s1.destination 上加入时间表 s2) 按 buses.bus_no;

排序