使用点分隔符查询MySQL LIKE

时间:2012-05-11 08:53:22

标签: mysql

我在mysql类型varchar中有字段,字段数据包含代码,代码就像树结构,点(。)作为父和子之间的分隔符。

示例1215包含子1215.0011215.002

这是数据库中每一行的数据

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

如何获得2级代码?
它的意思是只有代码1215.0011215.002

已经尝试过此查询

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

但它让所有代码都以1215开头,例如:1215.001.001

3 个答案:

答案 0 :(得分:4)

使用正则表达式。

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

这将匹配所有内容:

 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.("$")

答案 1 :(得分:2)

您可以使用正则表达式;

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

哪个匹配以^1215开头的项目,后跟句点.,后跟一个或多个数值[0-9]+,后跟字符串$的结尾

这将匹配1215.0011215.002,但不匹配12151215.001.001

希望它有所帮助, 戴夫

答案 2 :(得分:0)

select distinct substr(kode,1,8)  from `kegiatan` where `kode` LIKE '1215.%';

http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_substr