Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select non-duplicated records

I have a table with about 50 millions records.

the table structure is something like below and both callerid and call_start fields are indexed.

id -- callerid -- call_start

I want to select all records that their call_start is greater than '2013-12-22' and callerid is not duplicated before '2013-12-22' in whole table.

I used something like this:

SELECT DISTINCT 
  ca.`callerid` 
FROM
  call_archives AS ca 
WHERE ca.`call_start` >= '2013-12-22' 
  AND ca.`callerid` NOT IN 
  (SELECT DISTINCT 
    ca.`callerid` 
  FROM
    call_archives AS ca 
  WHERE ca.`call_start` < '2013-12-21')

but this is extremely slow, any suggestion is really appreciated.

like image 730
Mehdi Avatar asked Dec 26 '13 13:12

Mehdi


2 Answers

Try with NOT EXISTS

SELECT DISTINCT 
  ca.`callerid` 
FROM
  call_archives AS ca 
WHERE ca.`call_start` >= '2013-12-22' 
  AND NOT EXISTS 
  (SELECT 
    1 
  FROM
    call_archives AS cb 
  WHERE ca.`callerid` = cb.`callerid` 
    AND cb.`call_start` < '2013-12-21')
like image 140
M Khalid Junaid Avatar answered Oct 21 '22 18:10

M Khalid Junaid


Just curious if this query works fast or not on your table:

SELECT ca.`callerid` 
FROM call_archives 
GROUP BY ca.`callerid` 
HAVING MIN(ca.`call_start`) >='2013-12-22' 
like image 45
valex Avatar answered Oct 21 '22 18:10

valex