mysql同一行不同的列引用。(ifnull check)

时间:2014-07-28 05:21:01

标签: java mysql sql ifnull

我希望IFNULL检查同一行,但不同的列。

这是我的SQL示例。

SELECT 
    a.CONTACT_SEQ,
    'TEST' AS MEMO, 
    NOW() AS REG_DATE,
    a.USER_ID,
    a.NAME,
    a.CONTACT_NUM AS PHONE_NUM,
    (SELECT COUNT(*) FROM TB_CONTACT AS a,  TB_CONTACT_GROUP AS b
        WHERE
            b.USER_ID = 'spark@naver.com'
        AND
            b.GROUP_CONTACT_SEQ = 120
        AND
            a.GROUP_CONTACT_SEQ = b.GROUP_CONTACT_SEQ
    ) AS TOTCOUNT,
    IFNULL((SELECT * FROM tb_auto_ban WHERE user_id = 
'spark0017@naver.com' AND phone_num = a.CONTACT_NUM) , 'Y','N') AS define

FROM
        TB_CONTACT AS a, TB_CONTACT_GROUP AS b
            WHERE
                b.USER_ID = 'spark@naver.com'
            AND
                b.GROUP_CONTACT_SEQ = 120
            AND
                a.GROUP_CONTACT_SEQ = b.GROUP_CONTACT_SEQ


当我使用IFNULL时,如何将同一行引用到另一列?

1 个答案:

答案 0 :(得分:1)

在这种情况下你需要使用EXISTS:

SELECT 
    a.CONTACT_SEQ,
    'TEST' AS MEMO, 
    NOW() AS REG_DATE,
    a.USER_ID,
    a.NAME,
    a.CONTACT_NUM AS PHONE_NUM,
    (SELECT COUNT(*) FROM TB_CONTACT AS a,  TB_CONTACT_GROUP AS b
        WHERE
            b.USER_ID = 'spark@naver.com'
        AND
            b.GROUP_CONTACT_SEQ = 120
        AND
            a.GROUP_CONTACT_SEQ = b.GROUP_CONTACT_SEQ
    ) AS TOTCOUNT,
    CASE WHEN EXISTS(SELECT 1 FROM tb_auto_ban WHERE user_id = 
'spark@naver.com' AND phone_num = a.CONTACT_NUM) THEN 'Y' ELSE 'N' END AS define
FROM
        TB_CONTACT AS a, TB_CONTACT_GROUP AS b
            WHERE
                b.USER_ID = 'spark@naver.com'
            AND
                b.GROUP_CONTACT_SEQ = 120
            AND
                a.GROUP_CONTACT_SEQ = b.GROUP_CONTACT_SEQ