简体   繁体   中英

MySQL: improving efficiency of sub-select query

I have a set of (MySQL) tables as shown below. I need to retrieve a list of Trouble Tickets, as well as the id of matching equipment in either of the equipment tables, based on matching model/serial numbers.

Note that model/serial number combinations should be unique across both equipment tables, but the model/serial number entry boxes are free-form, so there's the possibility the user could enter the same model/serial twice. In such case, it doesn't matter which equipment unit is retrieved, but only result should be returned per ticket, since we're displaying a list of tickets, not equipment.

'tickets' [Trouble Tickets table]

  • id [index]
  • model [Equipment Model Number]
  • serial [Equipment Serial Number]
  • ... etc

user_equipment [User Equipment table]

  • id [index]
  • model [Equipment Model Number]
  • serial [Equipment Serial Number]
  • ... etc

site_equipment [Onsite Equipment]

  • id [index]
  • model [Equipment Model Number]
  • serial [Equipment Serial Number]
  • ... etc

Currently I'm using sub-queries to return the user and site equipment IDs, but performance is very poor:

SELECT tickets.*, ... other tables/columns here,
   (SELECT id FROM user_equipment WHERE model = tickets.model AND serial = tickets.serial LIMIT 1) as user_equipment_id,
   (SELECT id FROM site_equipment WHERE model = tickets.model AND serial = site_equipment.serial LIMIT 1) as site_equipment_id
FROM
  tickets
  ... other joins here
WHERE ... 
HAVING ... 
ORDER BY ...
LIMIT ...

I would greatly appreciate any suggestions for improving the performance of this query. Changing the table structure is, unfortunately, not an option at this point, due to many other dependencies.

Thanks!

You want indexes on:

  • user_equipment(model, serial, id)
  • site_equipment(model, serial, id)

The first two columns can be in either order.

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