SELECT * From `users` AS `User`
LEFT JOIN `selections` AS `Selections` ON (`Selections`.`user_id` = `User`.`id`)
LEFT JOIN `clients` AS `Client` ON (`Client`.`id` = `Selections`.`client_id`)
LEFT JOIN `client_stats` AS `ClientsStat` ON (`ClientsStat`.`date` = """DATE1""")
The thing is I would like to have the values of some fields in ClientsStat where date = “DATE1” minus the same fields but with a date #2 But I am not sure how can I do that while in a LEFT JOIN. I tried while doing an other LEFT JOIN to the same table and renaming it and subtracting but the execution time were extremely high so i guess my method was bad.
EDITING:
My result is something like:
USER => fields...
SELECTIONS => fields...
CLIENTS => fields..
CLIENT_STATS => field x,y,z on date = date 1
and so on.
I would like this:
USER => fields
USERSELECTIONS => fields...
CLIENTS => fields..
CLIENT_STATS => field x,y,z when client_stats.date = date1 MINUS field x,y,z when client_stats.date = date2
etc.
You should be good with a double join on the stats. Performance, I would guess is based on indexes. However, are you sure you mean left-join (only required on the first table regardless of match on the second). Or… do you mean an INNER JOIN — you are EXPECTING RECORDS ON BOTH SIDES of the join. If you are trying to subtract the values from one record date vs another, I would expect BOTH entries to be found. I’ve written as basis of a “JOIN” (both sides must exist) instead of “LEFT JOIN”.
Not absolutely sure if this is what you were looking for, but I would think one element you missed was a join to the client stats table on just the date… you had no qualifier on WHICH client ID and thus was probably the failure for your performance. Ensure client_Stats has an index on (client_id,date) — provided this IS the case that client_id was missing and IS part of the client_stats table.