Searching a column containing CSV data in a MySQL table for existence of input values

前端 未结 5 520
无人及你
无人及你 2020-12-19 16:53

I have a table say, ITEM, in MySQL that stores data as follows:

ID    FEATURES
--------------------
1     AB,CD,EF,XY
2     PQ,AC,A3,B3
3     AB,CDE
4     AB         


        
相关标签:
5条回答
  • 2020-12-19 17:31

    First of all, the database should of course not contain comma separated values, but you are hopefully aware of this already. If the table was normalised, you could easily get the items using a query like:

    select distinct i.Itemid
    from Item i
    inner join ItemFeature f on f.ItemId = i.ItemId
    where f.Feature in ('AB', 'PQ')
    

    You can match the strings in the comma separated values, but it's not very efficient:

    select Id
    from Item
    where
      instr(concat(',', Features, ','), ',AB,') <> 0 or
      instr(concat(',', Features, ','), ',PQ,') <> 0
    
    0 讨论(0)
  • 2020-12-19 17:32

    Alternatively, consider using RLIKE()

        select * 
          from ITEM
         where ','+FEATURES+',' RLIKE ',AB,|,PQ,'; 
    
    0 讨论(0)
  • 2020-12-19 17:32

    Just a thought:

    Does it have to be done in SQL? This is the kind of thing you might normally expect to write in PHP or Python or whatever language you're using to interface with the database.

    This approach means you can build your query string using whatever complex logic you need and then just submit a vanilla SQL query, rather than trying to build a procedure in SQL.

    Ben

    0 讨论(0)
  • 2020-12-19 17:48
    select * 
      from ITEM where 
     where CONCAT(',',FEAURES,',') LIKE '%,AB,%'
        or CONCAT(',',FEAURES,',') LIKE '%,PQ,%'
    

    or create a custom function to do your MATCH_ANY

    0 讨论(0)
  • 2020-12-19 17:54

    For all you REGEXP lovers out there, I thought I would add this as a solution:

    SELECT * FROM ITEM WHERE FEATURES REGEXP '[[:<:]]AB|PQ[[:>:]]';
    

    and for case sensitivity:

    SELECT * FROM ITEM WHERE FEATURES REGEXP BINARY '[[:<:]]AB|PQ[[:>:]]';
    

    For the second query:

    SELECT * FROM ITEM WHERE FEATURES REGEXP '[[:<:]]AB|PQ[[:>:]]' AND FEATURES REGEXP '[[:<:]]CDE[[:>:]];
    

    Cheers!

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