MySQL query finding values in a comma separated string

后端 未结 11 1374
孤独总比滥情好
孤独总比滥情好 2020-11-21 23:40

I have a field COLORS (varchar(50)) in a my table SHIRTS that contains a comma delimited string such as 1,2,5,12,15,. Each number repr

相关标签:
11条回答
  • 2020-11-21 23:52

    1. For MySQL:

    SELECT FIND_IN_SET(5, columnname) AS result 
    FROM table
    

    2.For Postgres SQL :

    SELECT * 
    FROM TABLENAME f
    WHERE 'searchvalue' = ANY (string_to_array(COLUMNNAME, ','))
    

    Example

    select * 
    from customer f
    where '11' = ANY (string_to_array(customerids, ','))
    
    0 讨论(0)
  • 2020-11-21 23:53

    You can achieve this by following function.

    Run following query to create function.

    DELIMITER ||
    CREATE FUNCTION `TOTAL_OCCURANCE`(`commastring` TEXT, `findme`     VARCHAR(255)) RETURNS int(11)
    NO SQL
    -- SANI: First param is for comma separated string and 2nd for string to find.
    return ROUND (   
        (
            LENGTH(commastring)
            - LENGTH( REPLACE ( commastring, findme, "") ) 
        ) / LENGTH(findme)        
    );
    

    And call this function like this

    msyql> select TOTAL_OCCURANCE('A,B,C,A,D,X,B,AB', 'A');
    
    0 讨论(0)
  • 2020-11-21 23:55

    All the answers are not really correct, try this:

    select * from shirts where 1 IN (colors);
    
    0 讨论(0)
  • 2020-11-21 23:59

    If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET type with FIND_IN_SET('red',colors) in your queries. When using the SET type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and" operation to check for presence of values which is way more efficient than scanning a comma-separated string.

    In SET('red','blue','green'), 'red' would be stored internally as 1, 'blue' would be stored internally as 2 and 'green' would be stored internally as 4. The value 'red,blue' would be stored as 3 (1|2) and 'red,green' as 5 (1|4).

    0 讨论(0)
  • 2020-11-22 00:02

    Take a look at the FIND_IN_SET function for MySQL.

    SELECT * 
        FROM shirts 
        WHERE FIND_IN_SET('1',colors) > 0
    
    0 讨论(0)
  • 2020-11-22 00:03

    If you're using MySQL, there is a method REGEXP that you can use...

    http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp

    So then you would use:

    SELECT * FROM `shirts` WHERE `colors` REGEXP '\b1\b'
    
    0 讨论(0)
提交回复
热议问题