php - 查询 : Find string in database field

标签 php mysql database

在我的数据库表中,我有三个字段。假设字段名称是 name、age 和 favorite_numbers。

现在,我的数据库内容如下:

  1. 安娜 15 岁,她最喜欢的数字是“14、21、16”
  2. Jessica 20 岁,她最喜欢的数字是“21、30、20”
  3. Sara 30 岁,她最喜欢的数字是“50、45、21”
  4. Jessa 12 岁,她最喜欢的数字是“10、12、20”
  5. Farrah 19 岁,她最喜欢的数字是“6、12、20”

如何制定我的查询以查看最喜欢的数字为 21 的人的姓名?

在上面的内容中,我只想显示 Anna、Jessica 和 Sara 的名字,因为他们三个的最喜欢的数字是 21。

最佳答案

看看使用 FIND_IN_SET(str,strlist)

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL.

SQL Fiddle DEMO

请注意使用

WHERE nums LIKE '%21%'

将不起作用,因为那样还包括 211 和 121

关于php - 查询 : Find string in database field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19602637/

相关文章:

java - 没有选择数据库 GAE

django - Docker 的 postgres 容器的密码验证失败

java - 在MySQL中根据条件检索数据

mysql - 备份和恢复数据库

php - Laravel 5.4 Blade foreach 循环

php - 将用户重定向到登录表单

php - 打开像页面一样的 href 到特定位置

php - 如何正确排序行中的数据

java - 为什么在这里找不到适合 mysql 消息的驱动程序?

mysql - 获取mysql中特定树的叶节点