I have a table that holds the configuration for some operation in my system. This operation can only be performed monthly, so my configuration table has a column for month and another column for year and it also points to a client (every client has a list of configurations). Whenever there is a change in the configuration, I add a new entry to my table with a new month and a new year and that is the active configuration from that time and on. For example: I have a configuration for 1-2020 with id=1 and another configuration for 5-2020 with id=2. If I run the operation for 3-2020 the active configuration would be id=1 because 3-2020 is smaller than 5-2020 but bigger than 1-2020.
I use this select to find the configuration for a client in a given month and year:
SELECT *
FROM configuration_table ct
WHERE CONCAT(ct.year, LPAD(ct.month, 2, '0')) =
(SELECT MAX(CONCAT(ct.year, LPAD(ct.month, 2, '0')))
FROM configuration_table ctInner
WHERE (ctInner.year < :year
OR
(ctInner.month <= :month
AND
ctInner.year = :year)
)
AND ctInner.client_id = client.id
);
My question is: if I have a large list of clients, I have to loop them and do this select for each one, which is very slow. I want to pass a list of client ids as parameter and bring the configuration_table entry for all of them at once, respecting the month and year.
I know this is a very specific question, but I am at a loss on how to do it. Any suggestion is appreciated, even the ones that change my model completely, as long as it serves the same purpose.