Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MySQL LIKE with dot separator

Tags:

mysql

i have field in mysql type varchar with field data contains code, and the code is like tree structure with dot (.) as separator between parent and child.

Example 1215 has child 1215.001 and 1215.002

And this is the data each row on database

ID  | kode
1   | 1215
2   | 1215.001
3   | 1215.001.001
4   | 1215.002.001
5   | 1215.002
6   | 1215.002.001

How to get the level 2 code?
which its mean will be only the code 1215.001 and 1215.002

Already tried with this query

select * from `kegiatan` where `kode` LIKE '1215.%';

But it get all the code start with 1215 eg: 1215.001.001

like image 771
GusDeCooL Avatar asked Mar 27 '26 10:03

GusDeCooL


1 Answers

Use a regular expression.

 select * from `kegiatan` where `kode` REGEXP '^1215\.[^\.]+$';

This will match everything:

 That starts with ( "^" )

 the string "1215.",

 followed by at least one character that is a member of the set "NOT ." ("[^\.]+")

  followed by the end of the string.("$")
like image 98
scragar Avatar answered Apr 02 '26 21:04

scragar



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!