I have a bridging table that looks like this
clients_user_groups
id = int
client_id = int
group_id = int
I need to find all client_id’s of of clients that belong to the same group as client_id 46l
I can achieve it doing a query as below which produces the correct results
SELECT client_id FROM clients_user_groups WHERE group_id = (SELECT group_id FROM clients_user_groups WHERE client_id = 46);
Basically what I need to find out is if there’s a way achieving the same results without using 2 queries or a faster way, or is the method above the best solution
You’re using a
WHERE-clause subquery which, in MySQL, ends up being reevaluated for every single row in your table. Use aJOINinstead:Since you plan on facilitating clients having more than one group in the future, you might want to add
DISTINCTto theSELECTso that multiple of the sameclient_idsaren’t returned when you do switch (as a result of the client being in more than one of client_id 46’s groups).If you haven’t done so already, create the following composite index on:
(client_id, group_id)With
client_idat the first position in the index since it most likely offers the best initial selectivity. Also, if you’ve got a substantial amount of rows in your table, ensure that the index is being utilized withEXPLAIN.