简体   繁体   English

具有两个输入列的MySQL CASE表达式

[英]MySql CASE expression with two input columns

I'm looking to use a case expression in mysql with two columns as input. 我正在寻找在mysql中使用case表达式并将两列作为输入的方法。 This is how I would like to format the code. 这就是我想要格式化代码的方式。 All code snippets use Set @a = 0; Set @b = 0; 所有代码段都使用Set @a = 0; Set @b = 0; Set @a = 0; Set @b = 0; at the start, although those values can be modified. 尽管可以修改这些值。 My own use case has several values each could be (more than 2 each). 我自己的用例每个都有几个值(每个都超过2个)。

SELECT 
    CASE (@a , @b)
        WHEN (0 , 0) THEN 'Both zero'
        WHEN (1 , 0) THEN 'a is 1'
        WHEN (0 , 1) THEN 'b is 1'
        WHEN (1 , 1) THEN 'both 1'
        ELSE NULL
    END;

When using the case statement this way, MySql throws Error Code: 1241. Operand should contain 1 column(s) . 当以这种方式使用case语句时,MySql会引发Error Code: 1241. Operand should contain 1 column(s) For reference, both of the following work, which makes me curious why the above doesn't. 作为参考,以下两项工作都使我感到奇怪,为什么以上都不行。

SELECT 
    IF((@a , @b) = (0 , 0),
        'Both zero',
        IF((@a , @b) = (1 , 0),
            'a is 1',
            IF((@a , @b) = (0 , 1),
                'b is 1',
                IF((@a , @b) = (1 , 1), 'both 1', NULL))));

and

SELECT 
    CASE
        WHEN (@a , @b) = (0 , 0) THEN 'Both zero'
        WHEN (@a , @b) = (1 , 0) THEN 'a is 1'
        WHEN (@a , @b) = (0 , 1) THEN 'b is 1'
        WHEN (@a , @b) = (1 , 1) THEN 'both 1'
        ELSE NULL
    END;

So, the question: Can I use a CASE expression like the first code snippet when doing a multi-column comparison? 所以,问题是:进行多列比较时,可以使用第一个代码片段之类的CASE表达式吗? If so, please provide an example. 如果是这样,请提供示例。 If not, why not? 如果没有,为什么不呢?

The 3rd method is completely viable for my own use case, but if @a and @b were select statements, it wouldn't be. 第三种方法对于我自己的用例是完全可行的,但是如果@a和@b是select语句,则不是。 The ideal would be a solution that: 理想的解决方案是:

  1. Only runs inputs once, if they were select statements. 如果输入是select语句,则仅运行一次。
  2. Can be easily expanded upon for any number of inputs. 可以轻松扩展为任意数量的输入。
  3. Is agnostic to the input types (IE (@a,@b) = (0,'!@#$:abc') is a valid case to check). 与输入类型无关(IE(@ a,@ b)=(0,'!@#$:abc')是要检查的有效情况)。

You can't use the short version of CASE with multiple values. 您不能将简短的CASE版本与多个值一起使用。 You need to use the long version that tests both conditions with AND 您需要使用测试AND两个条件的长版

CASE 
    WHEN @a = 0 AND @b = 0 THEN 'Both zero'
    WHEN @a = 1 AND @b = 0 THEN 'a is 1'
    WHEN @a = 0 AND @b = 1 THEN 'b is 1'
    WHEN @a = 1 AND @b = 1 THEN 'Both 1'
    ELSE NULL
END

Another option is to concatenate them. 另一个选择是将它们串联起来。

CASE CONCAT(@a, @b)
    WHEN '00' THEN 'Both zero'
    WHEN '10' THEN 'a is 1'
    WHEN '01' THEN 'b is 1'
    WHWN '11' THEN 'Both 1'
    ELSE NULL
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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