如何选择基于同一总线的路径记录

时间:2017-11-21 14:40:09

标签: php mysql

我有一个MYSQL表结构,如:

+----+--------+-------------+------------+
| id | bus_id | board_point | drop_point |
+----+--------+-------------+------------+
|  1 |      1 | Toronto     | Toronto    |
|  2 |      1 | Toronto     | Ottawa     |
|  3 |      1 | Ottawa      | Montreal   |
|  4 |      1 | Montreal    | Quebec     |
| 10 |      3 | Whistler    | Banff      |
| 12 |      2 | Toronto     | Montreal   |
| 16 |      2 | Toronto     | Toronto    |
+----+--------+-------------+------------+

如果他们有相同的bus_id,我想搜索board_point和drop_point。 例如:

  1. board_point = Toronto和drop_point =魁北克,结果是公共汽车1.
  2. board_point = Toronto和drop_point = Montreal,结果是1号和2号巴士。
  3. board_point = Toronto和drop_point = Banff,结果没有记录,因为它们不在同一条总线上。
  4. 如果我只使用board_point = X或drop_point = Y,则结果不正确。我的问题是如何从board_point = X或drop_point = Y的路径中选择*,并且它们必须在同一个bus_id中。

    非常感谢!

3 个答案:

答案 0 :(得分:5)

使用条件聚合

  SELECT bus_id,
         COUNT(CASE WHEN board_point = 'Toronto' THEN 1 END) as total_board,
         COUNT(CASE WHEN drop_point  = 'Quebec'  THEN 1 END) as total_drop
  FROM yourTable
  GROUP BY bus_id
  HAVING COUNT(CASE WHEN board_point = 'Toronto' THEN 1 END)  > 0
     AND COUNT(CASE WHEN drop_point  = 'Quebec'  THEN 1 END)  > 0

答案 1 :(得分:0)

select t.bus_id
from
   (
    select bus_id,drop_point
    from route
    where bus_id in (select distinct bus_id
                    from route
                    where board_point = 'Toronto'
                   )     
   )t
where t.drop_point = 'Quebec'
;

New DEMO

答案 2 :(得分:0)

在示例查询中使用MySQL IF,以便在board_pointdrop_point具有您寻求的特定值时给出正值。

  

当满足两个条件时,您需要结果,这意味着两者都有   found_in_boardfound_in_drop,在下面的示例查询中,是   阳性

SELECT `busid`,
         SUM(IF(`board` = "Toronto",1,0)) AS `found_in_board`,
         SUM(IF(`drop` = "Montreal",1,0)) AS `found_in_drop`
  FROM `buses`
  GROUP BY `busid`
  HAVING `found_in_board`  > 0
     AND `found_in_drop`  > 0;

SELECT `busid`,
         SUM(IF(`board` = "Toronto",1,0)) AS `found_in_board`,
         SUM(IF(`drop` = "Banff",1,0)) AS `found_in_drop`
  FROM `buses`
  GROUP BY `busid`
  HAVING `found_in_board`  > 0
     AND `found_in_drop`  > 0;

您可以在SQL Fiddle

中查看上述查询的输出