Let's say I have a table of clients and a table of "more_information".
I query the list of clients and their additional information (not every client has entries here, so we use LEFT JOIN):
SELECT id, name, more_information.data
FROM clients
LEFT JOIN more_information
ON more_information.client_id = clients.id
Now my problem: I want to query "more_information" only for clients that fulfill a condition, fe signed up in last 30 days, for the others I want just null for more_information.data
so something like (syntax not correct)
SELECT id, name, more_information.data
FROM clients
CASE WHEN clients.registered > '2015-12-27 00:00:00' THEN
LEFT JOIN more_information
ON more_information.client_id = clients.id
ELSE
null
END
I know I could use the CASE in the SELECT part, but that won't improve the performance what is my goal.
The reason is that the more_information JOIN queries a lot of data and has many additional conditions that make the query too slow. I don't want to query it where it is not necessary. Is that even possible with MySQL or do I need to split the query and make two separate queries?
Thanks a lot for your ideas
Just add to your JOIN condition
SELECT id, name, more_information.data
FROM clients
LEFT JOIN more_information
ON more_information.client_id = clients.id AND clients.registered > '2015-12-27 00:00:00'
An INDEX
on registered
, id
and client_id
would help performance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.