0

我有一个具有以下架构的表

UserId,notication_detail,notification_sent either 1 or 0 

对于不同的用户会有很多通知,比如 10 个通知userId=10或 4 个通知userId=3(意味着表中的 4 个不同行。可能没有针对特定 UserId 的通知。我想要做的是分别为所有用户获取未发送的通知,并且邮寄给他们。我不能在这里使用 UserId 分组。 select * from table where UserId="" and notification_sent=0这是 1 个用户的正常情况,但我需要检查该表的不同 ID

4

1 回答 1

0

假设您的数据库有这两个表: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)
于 2013-07-30T11:54:10.150 回答