是否有更好的方法(性能或语法)来编写以下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') ;
其目的是查找尚未为某个通知id推送通知的用户id
最佳答案
使用left join with is null
或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'
)
为了提高性能,如果尚未添加索引,则可能需要添加索引
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);
关于mysql - 联接中的负条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29273028/