2

Is there a better way (performance or syntax) to write the following mysql query:

Select un.user_id 
from user_notifications un
where un.notification_id  = 'xxxxyyyyyzzzz' 
and un.user_id not in (Select user_id from user_push_notifications upn 
where  upn.notification_id = 'xxxxyyyyyzzzz') ; 

The purpose is to find those user_id which have not been pushed a notification for a certain notification_id

Varun Jain
  • 1,801
  • 6
  • 31
  • 65

3 Answers3

1

You have many ways using left join with is null or not exists

Select 
un.user_id 
from user_notifications un
left join user_push_notifications upn 
on upn. user_id = un.user_id  and un.notification_id  = 'xxxxyyyyyzzzz' 
where upn. user_id is null

Select 
un.user_id 
from user_notifications un
where 
un.notification_id  = 'xxxxyyyyyzzzz' 
and not exists
(
 select 1 from user_push_notifications upn 
 where 
 un.user_id = upn.user_id 
 and upn.notification_id = 'xxxxyyyyyzzzz'
)

To boost the performance , you may need to add index if its not added yet

alter table user_notifications add index user_notifi_idx(user_id,notification_id);
alter table user_push_notifications add index user_notifp_idx(user_id,notification_id);
Abhik Chakraborty
  • 43,914
  • 5
  • 48
  • 61
  • `user_notifi_idx(user_id,notification_id)` --- this index will not work for your both queries. The order of columns must be the other way around. – zerkms Mar 26 '15 at 07:40
1

You can try the following, it is same as @Abhik's first answer but with one more condition.

SELECT DISTINCT un.user_id        -- This will give you unique users
FROM user_notifications un
LEFT JOIN
  user_push_notifications upn
ON
 upn.user_id = un.user_id
AND upn.notification_id = "xyz"   -- This will match with un by user_id for a specific notifioncation id.
WHERE un.notification_id = "xyz"  -- This will get only the specific notifications.
AND upn.notification_id IS null;  -- This will make sure that all the user_ids are filtered which exist in upn with specific notification id.
de-russification
  • 31,008
  • 6
  • 34
  • 52
bitkot
  • 4,428
  • 2
  • 26
  • 39
0

You can left join them like this

    Select un.user_id 
    from user_notifications un
    left join user_push_notifications upn
    on upn.user_id = un.user_id
    and un.notification_id  = 'xxxxyyyyyzzzz'
Bellash
  • 6,659
  • 6
  • 45
  • 82