简体   繁体   中英

MySQL query question

I have a database containing the route data for airlines. Some of the attributes are sources_airport_ID, destination_airport_ID, and airline(which supports the route from source to destination). I'm trying to self join the table to look up airlines that have the same route (in other words, same sources_airport_ID and destination_airport_ID).

I was using the query as follows: (table name = routes)

SELECT t1.*, t2.*
  FROM routes AS t1, routes AS t2
 WHERE t1.sources_airport_ID = t2.sources_airport_ID 
   AND t1.destination_airport_ID = t2.destination_airport_ID 
   AND t1.airline != t2.airline

When I execute this query, I get an error saying that the maximum execution time exceeded 300 seconds. I'm not sure if I'm using the correct query for this purpose. Can anyone help me with the query? I'm using xampp as my database.

Thanks in advance!

EDIT: My primary key is ID, which is just an auto-increment value. There are 64,114 records in routes table.

Try using JOIN syntax:

SELECT t1.*, t2.*
  FROM routes AS t1
  JOIN routes AS t2
  ON   t1.sources_airport_ID = t2.sources_airport_ID 
  AND  t1.destination_airport_ID = t2.destination_airport_ID 
  AND  t1.airline != t2.airline

But as suggested do make sure that the fields sources_airport_ID, destination_airport_ID and airline are indexed in the routes table.

Try something like this:

SELECT r.*, count(r.sources_airport_ID) as occ 
FROM routes r 
GROUP BY sources_airport_ID, destination_airport_ID, airline
HAVING occ > 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM