MYSQL AND query to satisfy on same column

前端 未结 2 1725
醉酒成梦
醉酒成梦 2020-12-05 07:28

Project Aim :

We are developing bus timing Api where user will search for buses.

Following are my table structure<

相关标签:
2条回答
  • 2020-12-05 07:39

    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.

    OQgraph (update)

    From symcbean in the comments, you could use the "OQgraph database engine" to do this too. There is an example of shortest path here.

    0 讨论(0)
  • 2020-12-05 07:58

    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;
    
    0 讨论(0)
提交回复
热议问题