MySQL query String contains

最后都变了- 提交于 2019-11-26 03:49:14

问题


I\'ve been trying to figure out how I can make a query with MySQL that checks if the value (string $haystack ) in a certain column contains certain data (string $needle), like this:

mysql_query(\"
SELECT *
FROM `table`
WHERE `column`.contains(\'{$needle}\')
\");

In PHP, the function is called substr($haystack, $needle), so maybe:

WHERE substr(`column`, \'{$needle}\')=1

回答1:


Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any character. Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.




回答2:


Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

  • INSTR



回答3:


WHERE `column` LIKE '%$needle%'



回答4:


Mine is using LOCATE in mysql:

LOCATE(substr,str), LOCATE(substr,str,pos)

This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.

In your case:

mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");



回答5:


In addition to the answer from @WoLpH.

When using the LIKE keyword you also have the ability to limit which direction the string matches. For example:

If you were looking for a string that starts with your $needle:

... WHERE column LIKE '{$needle}%'

If you were looking for a string that ends with the $needle:

... WHERE column LIKE '%{$needle}'



回答6:


be aware that this is dangerous:

WHERE `column` LIKE '%{$needle}%'

do first:

$needle = mysql_real_escape_string($needle);

so it will prevent possible attacks.




回答7:


You probably are looking for find_in_set function:

Where find_in_set($needle,'column') > 0

This function acts like in_array function in PHP



来源:https://stackoverflow.com/questions/2602252/mysql-query-string-contains

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