假设您的数据库有这两个表:User(UserID-PK,UserName,...)
然后Notification(NotificationID-PK,UserID,notification_sent,...)
您可以使用此查询为每个用户获取以下列:HasNotifications
(1,0) 和HasUnsentNotifications
(1,0) :
SELECT u.UserID,u.UserName,
CASE WHEN EXISTS(
SLEECT *
FROM Notification n
WHERE u.UserID=n.UserID ) THEN 1 ELSE 0 END HasNotifications,
CASE WHEN EXISTS(
SLEECT *
FROM Notification n
WHERE u.UserID=n.UserID AND n.notification_sent=0) THEN 1 ELSE 0 END HasUnsentNotifications
FROM User n
WHERE n.UserID IN (3,10,...)
但是,如果您需要一个包含没有通知的用户以及未发送通知的用户的列表,那么您可以使用另一个查询:
SELECT u.UserID,u.UserName,
CASE WHEN n.NotificationID IS NOT NULL THEN 1 ELSE 0 END HasNotifications,
n.NotificationID,n.notication_detail
FROM User u LEFT OUTER JOIN Notification n ON u.UserID=n.UserID
WHERE (n.notification_sent=0 -- Has unsent notifications
OR n.NotificationID IS NULL)
WHERE n.UserID IN (3,10,...)
编辑 1(SQL 服务器):
如果您不知道必须为多少用户运行查询,则可以使用表变量:
DECLARE @SelectedUsers TABLE(UserID INT PRIMARY KEY);
INSERT @SelectedUsers (UserID) VALUES (3);
...
INSERT @SelectedUsers (UserID) VALUES (10);
SELECT ...
FROM User n
WHERE n.UserID IN (SELECT UserID FROM @SelectedUsers)
或者
DECLARE @SelectedUsers TABLE(UserID INT PRIMARY KEY);
INSERT @SelectedUsers (UserID) VALUES (3);
...
INSERT @SelectedUsers (UserID) VALUES (10);
SELECT u.UserID,
CASE WHEN n.NotificationID IS NOT NULL THEN 1 ELSE 0 END HasNotifications,
n.NotificationID,n.notication_detail
FROM @SelectedUsers u LEFT OUTER JOIN Notification n ON u.UserID=n.UserID
WHERE (n.notification_sent=0 -- Has unsent notifications
OR n.NotificationID IS NULL)