0

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!

1 Answer 1

2

You want indexes on:

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

The first two columns can be in either order.

Sign up to request clarification or add additional context in comments.

5 Comments

So you're saying the existing query is OK and there's not a more optimal way to achieve this?
OK I added indexes and I'm blown away by the performance improvement! A query that originally took 5-8 seconds now takes 0.5 seconds! THANKS!
To clarify, is this the best way to write this type of query? I saw some people using LEFT JOIN and GROUP BY statements, but this adds a level of complexity and problems since I need to return many/all fields in multiple joined tables.
@RyanGriggs - "saw some people using..." -- Your situation seems to work well with the subqueries (with adequate composite indexes); some situations need LEFT JOIN and/or GROUP BY.
@RyanGriggs . . . Your query is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.