问题
I've got a basic question about mysql. In my table 'table' I've got a column named 'foo' (String). And I'd like to do something like this:
SELECT * FROM table WHERE %foo% LIKE '%thing%'
But it's obviously incorrect. Thanks in advance.
回答1:
SELECT * FROM table WHERE key like '%sth%'
回答2:
select * from table where key like '%sth%'
回答3:
Firstly key is a reserved keyword. So you may need to add square brackets quoted backticks around. Secondly you need to use the wildcard properly. Many answers have already shown you that. Set according to the sample data.
Set @sth:= 'joh'
Method 2 is to use REGEXP
.
Select * from mytable
where `key`
REGEXP @sth
;
Method 3 is to use instr
.
select * from landlord
where instr(`key`,@sth) > 0
;
You could also try match
against
. But it doesn't seem work very well with partial strings.
It's a FullText
search and your table has to be able to do that. MYISAM is the only table type that can do fulltext search. Assuming you do not have it enabled, then you may modity table using following Alter
lines. With FullText
search, you are infact adding an index on the key
column. Search becomes faster with indices.
`ALTER TABLE mytable ENGINE = MYISAM;`
Alter Table mytable
Add FULLTEXT(`key`)
;
Select * from mytable
where match(`key`)
against(%@sth% IN BOOLEAN MODE)
;
*SQLFIDDLE DEMO
来源:https://stackoverflow.com/questions/14116221/mysql-how-to-use-wildcards-in-where-clause-for-the-column-names-themselves