如何基于其他列的结果运行SELECT语句?

时间:2019-02-22 04:26:36

标签: mysql

我有一个像这样的MySQL表:

CREATE TABLE `my_table` (
  `col1` varchar(45) DEFAULT '',
  `col2` varchar(45) DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

它包含以下数据:

enter image description here

如何使用SELECT语句生成如下结果:

enter image description here

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;

其中???应该更改为其他内容。

3 个答案:

答案 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