无法获得JOIN工作
问题描述:
我有这两个表。第一张表包含巴士信息。第二表是多值,并且包含全部上述公共汽车的车站,在那里公共汽车将停下来拣选乘客。无法获得JOIN工作
问题陈述
假设有两辆公交车B1和B2具有相同的目标。如果用户选择站s1,我希望显示上面的总线。下面是表结构和我使用的查询(查询有时工作,但其他时间不)
表设计
Table 1
=======
BusId Source Destination DepartureTime
Table 2
=======
BusId StationName ArrivalTime DepartureTime
SELECT
b.BusId, b.BusNo, b.Source, b.Destination, b.SrcDepartureTime
AS SrcDepTime, b.DstArrivalTime AS DstArrTime, bs.StationName,
bs.ArrivalTime AS StationArrTime, bs.DepartureTime AS StationDepTime,
FROM
Buses b, BusStations bs
WHERE (b.BusId = bs.BusId) AND (b.Source = **passenger_source** OR bs.StationName = **passenger_source** OR bs.StationName = **passenger_dest**) AND ((DATE(b.SrcDepartureTime) = '2015-10-17') AND (DATE(bs.DepartureTime) = '2015-10-17')) GROUP BY bs.BusId;
正如我所说的,有时查询工作,但大多没有。我究竟做错了什么??感谢您的任何意见。
答
我写了下面的:
我的方案是从人站X出发,想要去的目的地y,则显示,停在站X的所有公交车,去到目的地为Y指定的时间。
我使用了相同的列名,所以应该很容易看到我所做的。
declare @goingto as nvarchar(50)
declare @goingfrom as nvarchar(50)
declare @time as datetime
set @goingto = 'Basingstoke'
set @goingfrom = 'Winchester'
set @time = '2015-10-17 18:50:00.000'
select i.BusID,i.Source,i.Destination,s.StationName,s.DepartureTime from BusInfo i
left join BusStops s on i.BusID = s.BusID
where i.Destination = @goingto and s.StationName = @goingfrom
and s.DepartureTime = @time
数据:
Table Bus Info
1 Southampton Basingstoke 2015-10-17 00:00:00.000
2 Portsmouth Basingstoke 2015-10-17 00:00:00.000
3 Bristol Winchester 2015-10-16 00:00:00.000
4 Winchester Bristol 2015-10-16 00:00:00.000
Table Bus Stops
1 Winchester 2015-10-17 12:00:00.000 2015-10-17 18:50:00.000
1 Basingstoke 2015-10-17 19:00:00.000 2015-10-17 19:10:00.000
1 RedBridge 2015-10-17 21:00:00.000 2015-10-17 21:10:00.000
2 Winchester 2015-10-17 12:00:00.000 2015-10-17 18:50:00.000
3 Basingstoke 2015-10-17 19:00:00.000 2015-10-17 19:10:00.000
2 Southampton 2015-10-17 17:50:00.000 2015-10-17 18:50:00.000
,你加载在sqlfiddle一个示例中,我们将有真正的设计和一些数据与 – Drew
玩,你也有在去年3个问题的答案给他们或者。看起来好像你没有把他们带到绿色复选标记的状态,或者完成你为什么不工作的想法等等。这就是我们在这里滚动的方式 – Drew
您正在使用“group by”,但“SELECT”中的大多数列没有聚合函数。因此,你会得到不确定的值。 –