我有以下表格:
具有主键和用户名的用户,例如
ID Username 1 Fred 2 John 3 Jack
具有主键和事件名称的事件
ID Eventname 1 Ferrari Road Show 2 Flower Show
UserStatusUpdates表,其中包含主键,状态更新和用户标识(外键)
ID UserID UserStatus 1 1 Really Good 2 1 Leaving Now 3 2 I concur
具有主键和两个外键(事件主键和用户主键)的事件参加者表
ID UserID EventID 1 1 1 2 2 1 3 3 1
我遇到的问题是我需要返回所有活动参与者及其最新状态更新,但有时用户实际上没有进行状态更新。
这就是我的查询:
SELECT EventAttendee.*, Users.UserName,Users.USERS_ID,
Users.ThumbnailPic,
Users.CountryName,
ISNULL(UserStatusUpdates.UserStatus,'No Updates')AS LastUpdate,
UserStatusUpdates.MediaTypeID,UserStatusUpdates.USERSTATUS_ID,(UserStatusUpdates.AddDate)
FROM EventAttendee
JOIN Users ON Events.UserID = Users.USERS_ID
OUTER APPLY (SELECT TOP 1 UserStatusUpdates.UserStatus,UserStatusUpdates.MediaTypeID,
UserStatusUpdates.USERSTATUS_ID,UserStatusUpdates.AddDate, UserStatusUpdates.UserID
FROM UserStatusUpdates where UserStatusUpdates.UserID = Users.USERS_ID
ORDER BY AddDate DESC) AS UserStatusUpdates WHERE UserStatusUpdates.UserID = EventAttendee.UserID
WHERE EventAttendee.EventID = @EventID
AND Users.bDeleted = 'False'
AND Users.bSuspended = 'False'
END
如何找回可能未进行更新的用户?
答案 0 :(得分:2)
您的查询有多个where子句,并且您已在子查询中指定UserStatusUpdates.UserID = Users.USERS_ID
联接。试试这个:
SELECT
EventAttendee.*,
Users.UserName,Users.USERS_ID,
Users.ThumbnailPic,
Users.CountryName,
ISNULL(UserStatusUpdates.UserStatus,'No Updates') AS LastUpdate,
UserStatusUpdates.MediaTypeID,
UserStatusUpdates.USERSTATUS_ID,
UserStatusUpdates.AddDate
FROM
EventAttendee
JOIN Users ON
Events.UserID = Users.USERS_ID
OUTER APPLY (
SELECT TOP 1
UserStatusUpdates.UserStatus,
UserStatusUpdates.MediaTypeID,
UserStatusUpdates.USERSTATUS_ID,
UserStatusUpdates.AddDate,
UserStatusUpdates.UserID
FROM
UserStatusUpdates
WHERE
UserStatusUpdates.UserID = Users.USERS_ID
ORDER BY
AddDate DESC
) AS UserStatusUpdates
WHERE
EventAttendee.EventID = @EventID
AND Users.bDeleted = 'False'
AND Users.bSuspended = 'False'
END