multiple values in mysql variable

后端 未结 6 2098
渐次进展
渐次进展 2021-02-05 13:49

The following works as expected when there is a single value stored in a variable.

SET @a := \"20100630\";
SELECT * FROM wordbase WHERE verified = @a;
         


        
6条回答
  •  耶瑟儿~
    2021-02-05 14:17

    You cannot (as far as I am aware) store multiple values in a MySQL user defined variable. What you have done is create a string which contains:

    '20100630', '20100701'
    

    That is not two separate values, but a single string value, just as this is a single string value:

    SET @a := "It's a single string, and that's the problem";
    

    You need to use two separate variables, or prepare a statement, like this:

    SET @a := "20100630";
    SET @b := "20100701";
    
    SET @sql = CONCAT(
        'SELECT * FROM wordbase WHERE verified IN (',
        @a,
        ',',
        @b,
        ')'
    );
    
    
    SELECT @sql;
    +--------------------------------------------------------------+
    | @sql                                                         |
    +--------------------------------------------------------------+
    | SELECT * FROM wordbase WHERE verified IN (20100630,20100701) |
    +--------------------------------------------------------------+
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    

    But that's kinda messy. Why do you need to use variables?

提交回复
热议问题