0

我有 2 张桌子,其中一张是“请求”,我有向其发送好友请求的用户,或者我收到了好友请求。在第二张表中,我为自己保留了入围用户的记录。现在,我想一起选择所有这些用户(我请求过的用户、请求过我的用户、我入围的用户)。我为此使用联合查询并根据列类型区分它们

select Distinct userid,type,status from
(
select RequestSenderId as UserId,'requestedme' as type,'1' as status from tblrequest where RequestReceiverId=@UserId 

union
select RequestReceiverId as UserId,'requestedbyme' as type,'2' as status from tblrequest where RequestSenderId=@UserId 

union
select Shortlisteduserid as UserId,'Shortlisted' as type,'0' as status from tblshortlist where userid=@UserId
)

问题是,如果我也将其列入候选名单,我将无法获得不同的用户 ID,并且他也向我发送了请求。

任何人都可以建议如何从结果中获得不同的用户 ID。优先级是按要求获取用户 ID,而不是入围。

4

3 回答 3

0

You can use a ranking function (ROW_NUMBER or DENSE_RANK) to prioritise results.

SELECT UserId, Type, Status
FROM (
    SELECT UserId, Type, Status
    , Priority = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY Type DESC)
    FROM (
        SELECT ReceiverId, RequestSenderId, 'requestedme', 1 FROM tblRequest
        UNION ALL
        SELECT SenderId, RequestReceiverId, 'requestedbyme', 2 FROM tblRequest
        UNION ALL
        SELECT UserId, Shortlisteduserid ,'Shortlisted', 0 FROM tblShortlist
    ) U (FilterUserId, UserId, Type, Status)
    WHERE FilterUserId = @UserId
) R
WHERE Priority = 1
于 2012-05-07T09:34:23.827 回答
0

这可以帮助你。

select userid,type,status from
(
select Distint  RequestSenderId ,'requestedme' as type,'1' as status from tblrequest where ReceiverId=@UserId 

union ALL
select Distint  RequestReceiverId ,'requestedbyme' as type,'2' as status from tblrequest where SenderId=@UserId 

union ALL
select Distint  Shortlisteduserid ,'Shortlisted' as type,'0' as status from tblshortlist where userid=@UserId
)
于 2012-05-07T06:39:42.120 回答
0

下面的呢?虽然它可能不是最有效的解决方案..

WITH requestedMe (userid, type, status)
    AS (
        SELECT RequestSenderId AS UserId,'requestedme' AS type,'1' AS status 
        FROM tblrequest 
        WHERE ReceiverId=@UserId)
    requestedByMe (userid, type, status)
    AS (
        SELECT RequestReceiverId AS UserId,'requestedbyme' AS type,'2' AS status 
        FROM tblrequest 
        WHERE SenderId=@UserId
            AND NOT EXISTS (
                SELECT *
                FROM requestedMe
                WHERE requestedMe.userid = tblrequest.RequestReceiverId))
    shortListed (userid, type, status)
    AS (
        SELECT Shortlisteduserid AS UserId,'Shortlisted' AS type,'0' AS status 
        FROM tblshortlist 
        WHERE userid=@UserId
            AND NOT EXISTS (
                SELECT *
                FROM requestedMe
                WHERE requestedMe.userid = tblshortlist.Shortlisteduserid)
            AND NOT EXISTS (
                SELECT *
                FROM requestedByMe
                WHERE requestedByMe.userid = tblshortlist.Shortlisteduserid))
SELECT userid, type, status
FROM requestedMe
UNION
SELECT userid, type, status
FROM requestedByMe
UNION
SELECT userid, type, status
FROM shortListed
于 2012-05-07T06:49:54.450 回答