如何获取未读通知(2个表与FK)

时间:2017-05-17 02:01:11

标签: php mysql sql notifications

我的数据库中有2个表:user_notificationuser_notification_read。这是一个用户通知系统,通知在user_notification上,当用户阅读通知时,它会在user_notification_read上存储通知id和用户id

CREATE TABLE `user_notification` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `related_user_id` int(11) NOT NULL,
 `text` text NOT NULL,
 `link` varchar(255) NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `user_notification_read` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `notification_id` int(11) NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`),
 KEY `notification_id` (`notification_id`),
 CONSTRAINT `user_notification_read_ibfk_1` FOREIGN KEY (`notification_id`) REFERENCES `user_notification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我想选择获取特定用户的未读通知数 (按用户ID)

我考虑过使用

JOIN/WHEREnotification.id = user_notification_read.notification_iduser_notification.user_id = X)从user_notification_read获取带CASE的行,以检查该行是否存在。如果它不存在,则在未读通知上+1。

我不知道这是否是实现它的合适逻辑,也不知道语法。我尝试了一些谷歌,但这些例子比我的情况更复杂,我认为这很简单。

我该怎么做?

小提琴:http://sqlfiddle.com/#!9/84a5ed/5/0

在小提琴示例中,用户 1 的未读通知计数 2

1 个答案:

答案 0 :(得分:0)

您应该使用left join

SELECT sum(r.notification_id is null)
FROM user_notification n
LEFT JOIN user_notification_read r ON r.notification_id = n.id
WHERE n.user_id = 1

r.notification_id is null表示未阅读通知。