加入中的负面条件

时间:2015-03-26 07:28:50

标签: mysql

编写以下mysql查询是否有更好的方法(性能或语法):

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') ; 

目的是找到那些尚未推送某个notification_id

通知的user_id

3 个答案:

答案 0 :(得分:1)

您可以通过多种方式使用left join with is nullnot 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'
)

为了提高性能,如果尚未添加索引,则可能需要添加索引

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);

答案 1 :(得分:1)

您可以尝试以下操作,它与@ Abhik的第一个答案相同,但还有一个条件。

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.

答案 2 :(得分:0)

你可以像这样加入他们

    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'