Slow Mysqli NOT EXISTS query

I am trying to pull available contract IDs. The table ‘shorttermID’ is simply a list of numbers from 2000 to 4000. These are the contact numbers that can be used. The table ‘carpark’ stores the bookings.

I need to see which contract numbers are currently being used and display all the other ones that are available.

There are 3 factors that determine if the contract ID is taken 1. The field ‘CarHere’ == ‘Y’
2. The return date (dc2) is greater than todays date.
3. the departdate (dc1) is less than todays date and the return date is empty.

This is the query I have…

[php]$clientID = new WA_MySQLi_RS(“clientID”,$georgeconnect_i,0);
$clientID->setQuery(“SELECT ID FROM shorttermID WHERE ID NOT IN (SELECT carpark.ShortTermID FROM carpark WHERE (CarHere =‘Y’ OR dc2 > date(‘Y-m-d’) OR (dc1 <= date(‘Y-m-d’) AND (dc2 IS NULL OR dc2=’’)))) ORDER BY ID”);
$clientID->execute();

[/php]
Is there a better way to do it as it takes about 20 seconds to run. I have indexed the fields in the database. There are about 20,000 records in the carpark table.

My first suggestion is to run explain to see where the query is being bogged down. I can’t help to much with the query as I don’t understand the structure well enough.

Thank you, I have never used EXPLAIN before. I am not sure what I am looking for. These are the results…

id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY shorttermAscarsID index NULL PRIMARY 4 NULL 2000 Using where; Using index
2 DEPENDENT SUBQUERY carpark range ShortTermID,dc2,CarHere,dc1 CarHere 2 NULL 2480 Using where

Sponsor our Newsletter | Privacy Policy | Terms of Service