Project Aim :
We are developing bus timing Api
where user will search for buses.
Following are my table structure
<
Also if buses are not directly travel between two city then i need to show inter connected buses.
That's a massive problem in a class of problems called routing problems.. For it, you need a better tool: consider migrating or integrating PostgreSQL, and examining PgRouting specifically you'll likely want Dijkstra's Shortest Path. PgRouting runs atop the PostGIS extension.
Or, consider working on integrating with Esri.
Alternatively you can mess around with this, but I wouldn't advise it.
From symcbean in the comments, you could use the "OQgraph database engine" to do this too. There is an example of shortest path here.
Because stop_id
cannot be two different values in the same row.
Aggregation is one way to do what you want:
SELECT b.bus_name
FROM buses b JOIN
route_connect rc
ON rc.busid = b.id JOIN
stops s
ON s.id = rc.stop_id
GROUP BY b.bus_name
HAVING SUM( s.stop_name = 'Sydney' ) > 0 AND
SUM( s.stop_name = 'Melbourne' ) > 0;
This returns buses that have stops with the name of both cities.
Given that buses can have lots of stops, it might be more efficient to do:
SELECT b.bus_name
FROM buses b JOIN
route_connect rc
ON rc.busid = b.id JOIN
stops s
ON s.id = rc.stop_id
WHERE s.stop_name in ('Sydney', 'Melbourne')
GROUP BY b.bus_name
HAVING COUNT(DISTINCT s.stop_name) = 2;