Tuesday, 1 October 2013

Convert MySQL query from a nested select to an inner join

Convert MySQL query from a nested select to an inner join

I have a nested select statement that works as it should, the only problem
is that it takes too long to run. I converted one of my other queries to
an inner join and it is much much faster. I'm trying to convert this query
to an inner join.
Current working query:
select date(datetime), req_origin, count( distinct session_id)
from LOG L1
where((datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and code_subcode in ('1001111','1001112','1001113','1001114'))
and ((
select count(*) from LOG L2 where L2.session_id = L1.session_id and
date(L2.datetime)
= date(L1.datetime)
and code_subcode in ('1001111','1001112','1001113','1001114')
) = 4)
group by date(datetime),req_origin order by date(datetime),req_origin;
This is what I've got for an inner join but it isn't working properly. It
only returns data when check for 1 matching code. When I query for 4
matching codes the query doesn't return anything.
select date(l1.datetime), l1.req_origin, count(distinct l1.session_id)
from LOG l1
INNER JOIN LOG l2 on l2.SESSION_ID = l1.SESSION_ID
where((l1.datetime >= str_to_date('2013-01-01 00:00:00','%Y-%m-%d %H:%i:%s'))
and (l1.datetime < str_to_date('2013-01-05 00:00:00','%Y-%m-%d %H:%i:%s'))
and l1.code_subcode in ('1001111','1001112','1001113','1001114')
and l2.code_subcode in ('1001111','1001112','1001113','1001114') = 4)
group by date(l1.datetime), l1.req_origin order by date(l1.datetime),
l1.req_origin;
Thanks in advance for any help!

No comments:

Post a Comment