I have a query that grabs information from four different tables, and joins them all. The tables are ‘guilds’, ‘guilds_memberships’, ‘flats’, and ‘users’. The query I have works, but i’m just wondering about the efficiency of it and if it can be made faster.
I mean at the moment it works fine and is speedy, but there isn’t much data inside of guilds_memberships, and it’s being COUNTED()’d. The query i’m using is shown below. (there will always be at least 1 record for each guild inside of guilds_memberships, flats, and users btw, if that’ll help with optimization at all (no reason to check for NULLs))
SELECT g.id, g.roomid, g.ownerid, g.roomid, g.state, g.name, g.description, g.badgestring, g.primarycolour, g.secondarycolour, g.created, u.username, f.FlatName, COUNT( m.guildid ) AS Members
FROM guilds g
INNER JOIN users u ON u.id = g.ownerid
INNER JOIN flats f ON f.FlatID = g.roomid
INNER JOIN guilds_memberships m ON m.guildid = g.id
WHERE g.id =1
LIMIT 0 , 30
Well, I don’t think you can do something to greatly improve performance of this query. It looks ok, and even performs great.
But, if it starts to perform less great, here are steps that I would do:
Break this query in parts. Retrieve guild info in one query, user info in another, etc. Let application code do the joining.
Cache what’s cacheable. I would bet that
u.usernameandf.FlatNamedon’t change too often, so you can load them once and keep in memory (or memcached).Purpose of these changes is to lessen load on the database. App servers (usually) are trivial to scale, just fire up more workers. Database, on the other hand, is one of the hardest to scale components.