MySQL将视图列从BIGINT更改为BIT

时间:2012-06-12 10:12:45

标签: mysql sql

我有一张这样的桌子。

(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存在的视图吗?

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

3 个答案:

答案 0 :(得分:3)

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

sqlfiddle上查看。

答案 1 :(得分: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 

答案 2 :(得分: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