mysql SELECT WHERE string contains characters

懵懂的女人 提交于 2019-12-24 14:01:20

问题



I have a table field events which can contains:

  • Only a sequence of number, for example: 45
  • or a sequence of number divided by the symbol |, for example 55|65|76

I think i have to use LIKE, but i don't know how. Can you help me?

Thanks


回答1:


I would recommend using CONCAT to add a pipe | before and after your field, and then using a LIKE search. Something like this:

SELECT *
FROM YourTable 
WHERE concat('|',field,'|') like '%|45|%'
  • SQL FIddle Demo

However, I highly recommend trying to normalize your data. Considering storing these in separate rows which would make searching/maintaining much easier.




回答2:


To fix your query, use:

Select * from tbl where events='45' or events like '%|45' or events like '%|45|%' or   
events like '45|%'

but this is terribly slow and should not be used.

Instead, do as Marc B states and create a child table events (ID, event).



来源:https://stackoverflow.com/questions/16775657/mysql-select-where-string-contains-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!