I have this SQL Query:
SELECT sequence, ticketnumber FROM tickets t
WHERE t.ticketnumber NOT IN (SELECT ticketnumber FROM ticket_updates)
it is querying thousands of rows in both tables - how can i make it run a little faster? Is there an alternative?
MySQL doesn't optimize this type of subquery well. It will keep running the second SELECT for every row in the outer query. Use a LEFT JOIN instead:
SELECT sequence, ticketnumber FROM tickets t LEFT JOIN ticket_updates tu ON (tu.ticketnumber = t.ticketnumber) WHERE tu.ticketnumber IS NULL;
Try this:
SELECT sequence, ticketnumber FROM tickets t
WHERE NOT EXISTS (SELECT u.ticketnumber FROM ticket_updates u WHERE u.ticketnumber = t.ticketnumber)
The NOT EXISTS
query is optimized for this situation (just seeing if a row does/doesn't exist). It's not the only option and other queries will evaluate to the same operation, but this is what I would choose because its clear what is being asked.
Also, for this particular query (the NOT EXISTS
), indexing ticket_updates.ticketnumber
would also yield a performance increase since the lookup speed would probably go from O(n)
to O(log(n))
or O(1)
(complete guess here...please correct me if I am utterly wrong).
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.