MySQL 查询字符串包含
我一直在试图弄清楚如何使用 MySQL 进行查询,检查某个列中的值(字符串 $haystack
)是否包含某些数据(字符串 $needle
>),像这样:
SELECT *
FROM `table`
WHERE `column`.contains('{$needle}')
在 PHP 中,该函数被称为 substr($haystack, $needle)
,所以也许:
WHERE substr(`column`, '{$needle}')=1
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:
SELECT *
FROM `table`
WHERE `column`.contains('{$needle}')
In PHP, the function is called substr($haystack, $needle)
, so maybe:
WHERE substr(`column`, '{$needle}')=1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
实际上非常简单:
%
是任何字符集(无、一个或多个)的通配符。请注意,这在非常大的数据集上可能会变慢,因此如果您的数据库增长,您将需要使用全文索引。Quite simple actually:
The
%
is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.使用:
参考:
Use:
Reference:
我的是使用
LOCATE
:此函数是多字节安全的,并且仅当至少一个参数是二进制字符串时才区分大小写。
在你的情况下:
Mine is using
LOCATE
in mysql:This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.
In your case:
除了@WoLpH 的回答。
使用
LIKE
关键字时,您还可以限制字符串匹配的方向。例如:如果您正在查找以
$needle
开头的字符串:如果您正在查找以
$needle
结尾的字符串: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
:If you were looking for a string that ends with the
$needle
:您可能正在寻找
find_in_set
函数:此函数的作用类似于
in_array< PHP 中的 /code>
函数
You probably are looking for
find_in_set
function:This function acts like
in_array
function in PHP请注意,这很危险:
首先执行:
这样可以防止可能的攻击。
be aware that this is dangerous:
do first:
so it will prevent possible attacks.
接受的答案对于 MySQL 来说是正确的,但由于问题是使用:
,看来作者想使用 PHP 构建 MySQL 查询。
由于这个问题是 12 年前提出的,当前的做法是使用预先准备好的语句来防止SQL注入。
以下是 PHP 的示例:
以下是用于构建 PHP PDO 语句的两个资源:
The accepted answer would be correct for MySQL alone, but since the question is using:
it appears the author wanted to construct the MySQL query using PHP.
Since the question was asked 12 years ago, current practice would be to use preprepared statements to prevent SQL injection.
Here is an example with PHP:
Here are two resources for building PHP PDO statements: