MySQL - how to use wildcards in WHERE clause for the column names themselves? [closed]

寵の児 提交于 2019-12-13 22:50:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!