Mysql REGEXP模式SELECT

时间:2014-03-28 17:44:47

标签: php mysql sql regex select

我想实现以下,用伪mysql代码编写。

数据库表(protected_paths.tbl):

ID  Path_Protected

1   /home/folder/private

2   /home/folder2/another-private

3   /home/folder3/subfolder/another/private-folder

4   /home/folder4/my_protected_folder

输入字符串:

Test | Match | String

1 | Y | /home/folder/private/another (caught by ID 1 above)

2 | Y | /home/folder/private/another/more (also caught by ID 1 above)

3 | N | /home/folder/work (not matched in table above)

4 | N | /home/folder/another-private (not matched in table above)

5 | N | /home/folder3/subfolder (not matched in table above - table above, ID 3, refers to deeper path)

显然不会起作用:

SELECT * FROM `protected_paths` WHERE Path_Protected = '/home/folder/private/another';

SELECT * FROM `protected_paths` WHERE Path_Protected REGEXP '/home/folder/private/another'; 

(我希望这与protected_pa​​ths.tbl中的ID 1匹配,因为它至少包含所有字符串)

非常感谢任何帮助。 干杯,达里尔

2 个答案:

答案 0 :(得分:0)

如果你有很多行,它就不会很快,但这样可行。

SELECT COUNT(*)<>0 
  from tbl 
 where 'test-string' LIKE CONCAT(path_protected,'%')

见这里:http://sqlfiddle.com/#!2/d6023/3/0

答案 1 :(得分:0)

不确定您是否需要REXEXP。您应该可以使用LIKECONCAT

完成此操作
SELECT * 
FROM protected_paths 
WHERE '/home/folder/private/another' LIKE CONCAT('%',Path_Protected,'%')