Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql SELECT WHERE string contains characters

Tags:

mysql

sql-like


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

like image 612
Lorenzo Tassone Avatar asked May 21 '26 05:05

Lorenzo Tassone


2 Answers

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.

like image 178
sgeddes Avatar answered May 22 '26 19:05

sgeddes


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).

like image 28
LuigiEdlCarno Avatar answered May 22 '26 17:05

LuigiEdlCarno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!