RKIDEV
RKIDEV

Reputation: 345

How to optimize MySQL query for counting 'userID' by joining 3 tables based on conditions? Current query is slow for large databases

I am trying to write mysql query using 3 tables and find the counts of 'userID'.

First, I have to select number of 'RefID' from records table between some date range, then select the number of 'AddressID' from refs table corresponds to the 'RefID', at last find counts of 'userID'(where userID like '174%') from addresses based on 'AddressID' matches between refs and addresses table.

Below is my query, the issue is that it's taking too much time and getting stuck in large database.

select count(DISTINCT (userID)) 
from db.addresses t 
where t.AddressID IN (
    select AddressID 
    from db.refs c 
    where c.RefID IN (
        select RefID 
        from db.records r         
        where r.StartDate >= '2022-06-30'
        and r.StartDate < '2022-07-01'
        )
    ) 
and t.userID like '174%';

Upvotes: 0

Views: 40

Answers (0)

Related Questions