我有一个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。 例如:
如果我只使用board_point = X或drop_point = Y,则结果不正确。我的问题是如何从board_point = X或drop_point = Y的路径中选择*,并且它们必须在同一个bus_id中。
非常感谢!
答案 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'
;
答案 2 :(得分:0)
在示例查询中使用MySQL IF
,以便在board_point
或drop_point
具有您寻求的特定值时给出正值。
当满足两个条件时,您需要结果,这意味着两者都有
found_in_board
,found_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
中查看上述查询的输出