(I have no idea how to title this question)
I have two tables: leads
and calls
leads
consists of unique lead_id
values for each lead and the associated phone_number
for that lead. There can be many leads with the same phone number.
calls
consists of lead_id
values for each call to a lead and the associated status
of each call. There is no phone_number
field in the calls
table.
I have the following query that will extract all phone numbers that do not have any calls in teh calls
table (regardless of lead_id) that resulted in the DEAD
status:
SELECT DISTINCT phone_number
FROM leads l
WHERE NOT EXISTS (
SELECT 1
FROM calls c
WHERE c.lead_id IN (
SELECT lead_id
FROM leads
WHERE phone_number = l.phone_number
)
AND c.status = "DEAD"
);
Now, I am trying to limit the results to only phone numbers that have at least 6 different lead_id
values in the calls
table.
Any ideas?
3
Answers
Join with the
calls
table, then useCOUNT(DISTINCT c.lead_id) >= 6
.In this example, leads_may_have_6 will be executed for O(N), all other are O(N^2). So shrinking leads to only numbers which already have 6 leads will greatly decrease execution time(I bet most time it will give zero results and will not execute another part at all).
But it is still questionable why you need leads which at least one times have DEAD status doesn’t matter what are other attempts.
Select with limit 1 will fetch exactly one row even if you have few thousands attempts for that lead id. Since it select 1, it will just check index and not fetch row at all if you have index on lead_id,status.
Here’s my understanding from the questions and comments:
Requirements
Definitions
calls
tablewhere status='DEAD'
lead_id
)Request
SQL Query