2

我有一个我无法解决的问题!(sqlite3,但我认为它与 MySql 相同)我有这些表(图片):

替代文字 http://www.radarkiller.fr/blog/bddprobleme.png

而且我想找到通往两条不同街道的所有公交线路(带有类型和编号),我从中获得了 street_id(例如 12 和 14)。

结果应向客户提供城市中从第 12 号街道到第 14 号街道的所有公交线路(编号、类型和编号)(示例)。

就像 Larry Lustig 说的那样,您可以使用两个邻域外键创建快捷方式。

预先感谢您的帮助 !

4

2 回答 2

4

使用分组/计数:

  SELECT t.bus_line_id,
         t.bus_line_type,
         t.bus_line_number
    FROM BUS_LINE t
    JOIN LINK_BUS_NEIGBOURHOOD lbn ON lbn.bus_line_id = t.bus_line_id
    JOIN LINK_NEIGHBOURHOOD_STREET lns ON lns.neighbourhood_id_ns = lbn.neighbourhood_id_ns
    JOIN STREET s ON s.street_id = lns.street_id
   WHERE s.street_id IN (12, 14)
GROUP BY t.bus_line_id,
         t.bus_line_type,
         t.bus_line_number,
         s.street_id
  HAVING COUNT(DISTINCT s.street_id) = 2

使用 JOIN:

SELECT t.bus_line_id,
       t.bus_line_type,
       t.bus_line_number
  FROM BUS_LINE t
  JOIN LINK_BUS_NEIGBOURHOOD lbn ON lbn.bus_line_id = t.bus_line_id
  JOIN LINK_NEIGHBOURHOOD_STREET lns ON lns.neighbourhood_id_ns = lbn.neighbourhood_id_ns
  JOIN STREET s ON s.street_id = lns.street_id
               AND s.steet_id = 12
  JOIN STREET s2 ON s2.street_id = lns.street_id
                AND s2.steet_id = 14
于 2009-10-09T02:41:00.790 回答
2

假设您希望样本结果集中有三个单独的记录,并假设所有“neighborhood_id”列都是返回到邻域表的 FK,请尝试:

SELECT * 
  FROM bus_line 
 WHERE EXISTS (SELECT * 
                 FROM neighborhood N 
           INNER JOIN link_neighborhood_street S ON N.neighborhood_id = S.neighborhood_id_ns 
                WHERE S.street_id = 12) 
  AND EXISTS (SELECT * 
                FROM neighborhood N 
          INNER JOIN link_neighborhood_street S ON N.neighborhood_id = S.neighborhood_id_ns 
               WHERE S.street_id = 14);
于 2009-10-09T02:43:58.160 回答