mysql check if numbers are in a comma separated list

前端 未结 7 1948
萌比男神i
萌比男神i 2020-11-27 06:13

I have a table like this:

UID(int) NUMBERS(blob)
----------------------
1        1,13,15,20
2        3,10,15,20
3        3,15

And I would l

相关标签:
7条回答
  • 2020-11-27 06:37

    The function complete for you

    DELIMITER $$
    
    CREATE FUNCTION `FIND_IN_SET_X`(inputList TEXT,targetList TEXT) RETURNS INT(11)
        DETERMINISTIC
    BEGIN
      DECLARE limitCount INT DEFAULT 0 ;
      DECLARE counter INT DEFAULT 0 ;
      DECLARE res INT DEFAULT 0 ;
      DECLARE temp TEXT ;
      SET limitCount = 1 + LENGTH(inputList) - LENGTH(REPLACE(inputList, ',', '')) ;
      simple_loop :
      LOOP
        SET counter = counter + 1 ;
        SET temp = SUBSTRING_INDEX(SUBSTRING_INDEX(inputList, ',', counter),',',- 1) ;
        SET res = FIND_IN_SET(temp, targetList) ;
        IF res > 0 
        THEN LEAVE simple_loop ;
        END IF ;
        IF counter = limitCount 
        THEN LEAVE simple_loop ;
        END IF ;
      END LOOP simple_loop ;
      RETURN res ;
    END$$
    
    DELIMITER ;
    
    0 讨论(0)
  • 2020-11-27 06:49

    Not the most pretty solution, but it works:

    select
       UID
    from
       YOUR_TABLE
    where
       find_in_set('3', cast(NUMBERS as char)) > 0
       and
       find_in_set('15', cast(NUMBERS as char)) > 0
    

    Note that it's string comparison, so you may need to cast your input parameters to char as well.

    0 讨论(0)
  • 2020-11-27 06:49

    find_in_set_x

    create a new function in mysql and paste in the following (not my work by the way)

    BEGIN
    DECLARE limitCount INT DEFAULT 0;
    DECLARE counter INT DEFAULT 0;
    DECLARE res INT DEFAULT 0;
    DECLARE temp TEXT;
    SET limitCount = 1 + LENGTH(inputList) - LENGTH(REPLACE(inputList, ',',''));
    simple_loop:LOOP
    SET counter = counter + 1;
    SET temp = SUBSTRING_INDEX(SUBSTRING_INDEX(inputList,',',counter),',',-1);
    SET res = FIND_IN_SET(temp,targetList);
    IF res > 0 THEN LEAVE simple_loop; END IF;
    IF counter = limitCount THEN LEAVE simple_loop; END IF;
    END LOOP simple_loop;
    RETURN res;
    END
    
    0 讨论(0)
  • 2020-11-27 06:52

    Try This query :

    SELECT UID FROM table WHERE NUMBERS REGEXP "[[:<:]](3|10)[[:>:]]"
    
    0 讨论(0)
  • 2020-11-27 06:57

    You Can Try As Like Following :

     SELECT * FROM table_name WHERE FIND_IN_SET('3', NUMBERS) AND  FIND_IN_SET('15', NUMBERS)
    
    0 讨论(0)
  • 2020-11-27 06:57

    Also check if this is helpful to anyone

    An Extended function to eliminate the limitation of native FIND_IN_SET() in MySQL, this new extended version FIND_IN_SET_X() provides feature to compare one list with another list.

    i.e.

    mysql> SELECT FIND_IN_SET_X('x,c','a,b,c,d'); -> 3 
    

    Checkout this link for more details.

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