[英]check if id not exist in join table
我有两张桌子。 表I和表II包含的消息包含用户名ID和消息ID。 在看到表II中记录的消息后,我做了每个用户。 如果用户尚未阅读消息,我想通知。 最快,最有效的方法是什么?
tbl_msg
id title msg user_id ucid all
1 msg1 text * *
2 msg2 text
tbl_msg_log
id user_id msg_id
1 2 2
2 1 2
我知道使用foreach太旧了。 所以我怎么能加入两个表并检查表msg日志中是否不存在user_id和msg_id?
更新1
我用这个SQL,但不起作用:
$get_msg_notifiction = $pdo->query("SELECT * FROM `tbl_msg` WHERE (`user_id`='$user[id]' OR `ucid`='$user[group_id]' OR `all`='1') AND NOT EXISTS (SELECT id FROM tbl_msg_log WHERE tbl_msg.id = tbl_msg_log.msg_id AND tbl_msg_log.user_id = $user[id])");
返回:
Fatal error: Call to a member function execute()
使用不存在:
select * from tbl_msg
where not exists (select 1 from tbl_msg_log
where tbl_msg.id = tbl_msg_log.msg_id)
如果您确实必须加入:
select tbl_msg.*
from tbl_msg left join tbl_msg_log
on tbl_msg.id = tbl_msg_log.msg_id
where tbl_msg_log.msg_id is null
这列出了尚未阅读的消息
SELECT tbl_msg.*
FROM tbl_msg_log
LEFT JOIN tbl_msg
ON tbl_msg_log.msg_id=tbl_msg.id
WHERE tbl_msg.id IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.