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

前端 未结 5 556
无人及你
无人及你 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
    

提交回复
热议问题