模式在字段中时如何编写查询

时间:2012-02-12 22:06:12

标签: mysql design-patterns wildcard sql-like

我有一张表,其中一个字段包含'hey *'或'%test%'等模式。 像这样:

Id - f_pattern - f_Respond
1  - 'hey *' - 'hello there'
2  - 'how are you *' - 'am fine'

有可能我写这样的查询:

select * from table where f_pattern like 'hey bobby'

并返回第一行?

2 个答案:

答案 0 :(得分:4)

是的,如果您将模式更改为“兼容”值,并颠倒相似的逻辑:

select * from pattern_table
where 'hey bobby' like replace(f_pattern, '*', '%')

答案 1 :(得分:1)

你试过吗

select * from `table` where field like 'hey %'

//修改

它让我感到惊讶,但这很有效:

create database test;    
use test;
create table pattern (a varchar (100));
insert into pattern values ('a%');
create table subject (a varchar (100));    
insert into subject values ('abc'), ('cde');
select * from subject where a like (select a from pattern limit 1);

-- result
-- +------+
-- | a    |
-- +------+
-- | abc  |
-- +------+
-- 1 row in set (0.03 sec)

请参阅:http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html