1

我有一张这样的桌子。

(BIGINT)     (BIGINT)
PLAYER_ID    FRIEND_ID
----------------------
1            2
2            1
1            3

我想我可以将视图设为

SELECT * FROM FRIEND F1 LEFT OUTER JOIN FRIEND F2 ON F1.FRIEND_ID = F2.PLAYER_ID

印刷

F1.PLAYER_ID    F1.FRIEND_ID    F2.PLAYER_ID    F2.FRIEND_ID
[BIGINT]        [BIGINT]        [BIGINT]        [BIGINT]
------------------------------------------------------------
1               2               2               1
2               1               1               2
1               3               NULL            NULL

我可以制作一个代表那些 F2 作为 BIT 存在的视图吗?

F1.PLAYER_ID    F1.FRIEND_ID    BACK
[BIGINT]        [BIGINT]        [BIT]
-------------------------------------
1               2               1     // exist (1 -> 2)
2               1               1     // exist (2 -> 1)
1               3               0     // no backing relation (3 -> 1)

更新 - - - - - - - - - - - - - - - - - - - - - - - - - -----------------

抱歉,上面的查询并不完美。

带有@Romil 答案的查询必须这样写。

SELECT
    F1.PLAYER_ID,
    F1.FRIEND_ID,
    CASE WHEN F2.FRIEND_ID IS NULL THEN 0 ELSE 1 END AS BACK
FROM FRIEND F1
    LEFT OUTER JOIN FRIEND F2
        ON F1.FRIEND_ID = F2.PLAYER_ID AND F1.PLAYER_ID = F2.FRIEND_ID
4

3 回答 3

3
SELECT *, EXISTS (SELECT * FROM FRIEND WHERE PLAYER_ID = F1.FRIEND_ID) AS BACK
FROM   FRIEND AS F1

sqlfiddle上查看。

于 2012-06-12T10:15:19.780 回答
2
SELECT F1.PLAYER_ID, 
       F2.PLAYER_ID, 
       CASE 
         WHEN F2.PLAYER_ID IS NULL THEN 0 
         ELSE 1 
       end AS Back 
FROM   FRIEND F1 
       LEFT OUTER JOIN FRIEND F2 
                    ON F1.FRIEND_ID = F2.PLAYER_ID 
于 2012-06-12T10:15:11.497 回答
1

你可以尝试一些类似的东西

SELECT F1.*, if(F1.FRIEND_ID = F2.PLAYER_ID,1,0) FROM FRIEND F1 LEFT JOIN FRIEND F2 ON F1.FRIEND_ID = F2.PLAYER_ID
于 2012-06-12T10:17:27.983 回答