我有一个像这样的MySQL表:
CREATE TABLE `my_table` (
`col1` varchar(45) DEFAULT '',
`col2` varchar(45) DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
它包含以下数据:
如何使用SELECT
语句生成如下结果:
check
列内容的含义如下:
`both` when both `col1` and `col2` have values.
`left` when only `col1` has a value.
`rightest` when only `col2` has a value.
`empty` when both `col1` and `col2` has empty value.
我认为查询看起来像这样
# something must be used to replace ???
SELECT (???) AS check, col1, col2 FROM my_table;
其中???
应该更改为其他内容。
答案 0 :(得分:2)
使用CASE WHEN
表达式
SELECT CASE WHEN col1 = '' and col2='' then 'Empty'
WHEN col1 = '' then 'Right'
WHEN col2='' then 'Left'
else 'Both' end as 'Check',
col1, col2 FROM yourtablename
答案 1 :(得分:0)
下面是查询-
select
col1, col2,
case
when (nvl(col1) or col1='') and (nvl(col2) or col2='') then 'empty'
when (nvl(col1) or col1='') and (col2<>'') then 'right'
when (col1<>'') and (nvl(col2) or col2='') then 'left'
else 'Both' end as col3 from mytable
答案 2 :(得分:0)
情况何时可以满足您的要求:
SELECT CASE WHEN col1 = ''
THEN CASE WHEN col2 = ''
THEN 'empty'
ELSE 'right'
END
ELSE CASE WHEN col2 = ''
THEN 'left'
ELSE 'both'
END AS check,
col1, col2 FROM my_table