简体   繁体   中英

sql rewrite for case statement

I'm using a case statement and wondering if there is a better way to write this?

This is what I currently have and it works:

select 
CASE WHEN ug.permissions = "" OR ug.permissions IS NULL
THEN
    g.permissions
ELSE
     ug.permissions 
END as permissions,
CASE WHEN ug.display = "" OR ug.display IS NULL
THEN
    g.display
ELSE
     ug.display 
END as display
from system.users_groups as ug
inner join system.groups as g on ug.group_id = g.id
where ug.user_id = ?

I was thinking something more like this but I have very little experience with case statements in sql:

select 
CASE WHEN ug.permissions = "" OR ug.permissions IS NULL
THEN
    g.permissions,
    g.display
ELSE
    ug.permissions,
    ug.display
END
from system.users_groups as ug
inner join system.groups as g on ug.group_id = g.id
where ug.user_id = ?

I prefer the following:

SELECT
  g.id,
  IFNULL(NULLIF(ug.permission, ''), g.permission),
  IFNULL(NULLIF(ug.display, ''), g.display)
FROM groups AS g

INNER JOIN users_group AS ug
ON ug.group_id = g.id

SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM