How to use an user variables in MySQL LIKE clause?

后端 未结 7 2064
逝去的感伤
逝去的感伤 2020-12-03 02:43

I am trying to setup a few simple SQL scripts to help with some short term DB administration. As such, I\'m setting up variables to try to make it easier to reuse these scri

相关标签:
7条回答
  • 2020-12-03 02:58
    SET @email = 'test@test.com';
    
    SELECT email from `user` WHERE email LIKE CONCAT('%', @email, '%');
    
    0 讨论(0)
  • 2020-12-03 03:00
    BEGIN 
        SET @emailid = CONCAT('%', 'email@email.com' ,'%');
        SET @t1 =CONCAT('SELECT * FROM user WHERE email LIKE ''', @emailid, '''');
        PREPARE stmt3 FROM @t1;
        EXECUTE stmt3;
        DEALLOCATE PREPARE stmt3;
    END
    
    0 讨论(0)
  • 2020-12-03 03:03

    Using same syntax as oracle seems to work:

    SELECT email from user WHERE email LIKE '%' || @email || '%';

    0 讨论(0)
  • 2020-12-03 03:10

    I resolved using the CONCAT function before using LIKE statement:

    SET @email = 'test@test.com';
    set @email = CONCAT('%',@email,'%');
    SELECT email from `user` WHERE email LIKE @email;
    

    It works fine for me

    0 讨论(0)
  • 2020-12-03 03:13

    You may have error

    Error Code: 1267. Illegal mix of collations for operation 'like'    0.016 sec
    

    In this case you need to specify the same collation as used for your table like that:

    SET @email = 'test@test.com' COLLATE utf8_unicode_ci;
    
    0 讨论(0)
  • 2020-12-03 03:15

    Works without concat():

    LIKE '%{$var}%'
    

    (Mysql version 5.+)

    0 讨论(0)
提交回复
热议问题