Reputation: 37
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.
Upvotes: 1
Views: 243
Reputation: 81557
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.
Upvotes: 1
Reputation: 301
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;
Upvotes: 0