This is not a huge advice but it might help a little bit.
I should the replace php variables like this : " WHERE m.version = '".VERSION."' " to something like : " WHERE m.version = :version " and set the ":version" value in the code later before you execute. The DB will get more performance because this will your query is always the same. in your approach you change the query everytime so the Db need to do all the parse again, in my example we just change the value not the query and this can save same processing time.
Also if you need to keep historic data from your tables, my adivice is not create something new everytime, just create a flag like FL_VISIBLE to ignore the old version registers.After that you might create index that will help your query to work faster.Once you do the same query over and over again you should create an index in the fields that you use there, so it will become faster.
I hope that this help you to improve your results.
Kind Regards,