根据另一列中的两个值选择列值

Yon*_*kee 5 mysql

我正在使用下表:

1   0051ML66220600132482    06:00:00        06:00:00        1538    100 0   1
2   0051ML66220600132482    06:00:00        06:00:00        1540    200 0   0
3   0051ML66220600132482    06:00:00        06:00:00        1541    300 0   0
4   0051ML66220600132482    06:01:00        06:01:00        1542    400 0   0
5   0051ML66220600132482    06:01:00        06:01:00        1543    500 0   0
6   0051ML66220600132482    06:02:00        06:02:00        1544    600 0   0
7   0051ML66220600132482    06:03:00        06:03:00        1546    700 0   0
Run Code Online (Sandbox Code Playgroud)

表结构如下:

------------------------------------------------------------------
--  TABLE stop_times
------------------------------------------------------------------ 
CREATE TABLE stop_times 
( 
    id int(12),   
    trip_id varchar(100),
    arrival_time varchar(8),
    arrival_time_seconds int(100),
    departure_time varchar(8),
    departure_time_seconds int(100),
    stop_id varchar(100),
    stop_sequence varchar(100),
    pickup_type varchar(2),
    drop_off_type varchar(2)
);
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取DISTINCT trip_id它是否与目的地和到达相匹配stop_id

我尝试了下面的 SQL,但没有成功:

select DISTINCT trip_id from stop_times where stop_id=1538 AND stop_id =1540;
Run Code Online (Sandbox Code Playgroud)

它应该在哪里产生:0051ML66220600132482

我也尝试过INNER JOIN如下:

SELECT 
    t.trip_id,
    start_s.stop_name as departure_stop,
    end_s.stop_name as arrival_stop
FROM trips t 
INNER JOIN stop_times start_st ON t.trip_id = start_st.trip_id
INNER JOIN stops start_s ON start_st.stop_id = start_s.stop_id
INNER JOIN stop_times end_st ON t.trip_id = end_st.trip_id
INNER JOIN stops end_s ON end_st.stop_id = end_s.stop_id
WHERE 
   start_s.stop_id = 1538 
  AND end_s.stop_id = 1540;
Run Code Online (Sandbox Code Playgroud)

但它太慢了,这个简单的查询大约需要 8-15 秒。

解释补充:

在此输入图像描述

编写此查询的最快/最佳方法是什么?

Mat*_*att 3

如果我理解,您想要获取表中出现的所有 trip_id 值,针对一行或多行上的一个 stop_id ,以及针对其他行上的另一个 stop_id 。这应该可以做到:

select trip_id 
from stop_times 
where stop_id = 1538 
or stop_id = 1540
group by trip_id
having count(distinct stop_id) > 1;
Run Code Online (Sandbox Code Playgroud)

示例: http: //sqlfiddle.com/#!9/ e78aa/1

请注意,trip_id 0051ML66220600132483 在一站匹配,但在另一站不匹配,因此不会返回。