如果列为空,则mysql select语句将返回列

时间:2014-09-10 22:32:41

标签: sql mysqli inner-join

有没有办法select col1 if col2 is empty else use col2col1永远不会是空的。

$sql = 'select 
        ug.permissions,
        g.name,
        g.display,
        g.permissions
        from system.users_groups as ug
        inner join system.groups as g on ug.group_id = g.id
        where ug.user_id = ' . $_SESSION['user_id'];

上面的语句带回了两个权限列,我想只返回一个权限列。

if ug.permissions = '' then use g.permissions

1 个答案:

答案 0 :(得分:3)

使用COALESCE和NULLIF:

$sql = 'select 
        COALESCE(NULLIF(ug.permissions,''),g.permissions) as permissions ,
        g.name,
        g.display
        from system.users_groups as ug
        inner join system.groups as g on ug.group_id = g.id
        where ug.user_id = ' . $_SESSION['user_id'];

使用CASE:

$sql = 'select 
        CASE WHEN ug.permissions = '' OR ug.permissions IS NULL
        THEN
             g.permissions
        ELSE
             ug.permissions 
        END as permissions ,
        g.name,
        g.display
        from system.users_groups as ug
        inner join system.groups as g on ug.group_id = g.id
        where ug.user_id = ' . $_SESSION['user_id'];