SQL中没有三目运算符,可以使用case when then
替代。
SELECT
o.id,
-- 以下两句写法不一样,但作用一样
(case o.division_code when '-1' then '全国' else dv.name end) as division_name,
(case when o.division_code = '-1' then '全国' else dv.name end) as division_name2,
FROM
tb_organization o
LEFT JOIN tb_division dv ON o.division_code = dv.`code`
WHERE
o.id = 67
根据o.division_code
字段的值,如果为-1
,那么显示全国
;
如果不为-1,那么则查出对应的name
.
需要注意的一点:对Null的判断
MySQL中使用case when then
判断某字段是否为null
,不能使用上面的第一种写法,应该使用第二种写法,且不是=
, 而是is
.
如:
(case when o.parent_id is null then '顶级节点' else o2.name end) as parent_organization_name
更详细的,请见:SQL之case when then用法