Chinaunix首页 | 论坛 | 博客
  • 博客访问: 311044
  • 博文数量: 163
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: -40
  • 用 户 组: 普通用户
  • 注册时间: 2017-03-08 00:28
文章分类

全部博文(163)

文章存档

2015年(2)

2014年(35)

2013年(28)

2012年(30)

2011年(22)

2010年(14)

2009年(8)

2008年(13)

2007年(11)

分类: Mysql/postgreSQL

2014-06-07 09:35:10

Generally, We stores various values of choices in same a column of mysql database. For example we store user’s preferred categories in user table’s preferred_categories(varchar(250)) field(column). Value stored in this field may be like 1,2,5,6,1

1,18 or any of similar pattern. It would be difficult to get all user whose preferred category would be “1″. If you use like query “preferred_categories LIKE ’1%’” then it also get matched with 1 & 11.

There is one of the good functions from MySQL which help to solve this problem. FIND_IN_SET() function is use to match among comma separated values. Basically FIND_IN_SET() function is use with SET type of datatype but it’s compatible to use with any other datatype where values get stored as comma separated.

mysql string function is FIND_IN_SET and its returns the position of a string value if it is available (as a substring) within a string. String contain comma separated characters or values.

This function returns 0 when search string does not exist in the string.

SYNTAX:

   SELECT FIND_IN_SET('1',preferred_categories);

Above syntax, ‘1’ is the string/value used for find within preferred_categories.

So Where query would be similar to following:

   SELECT cat_name FROM category WHERE FIND_IN_SET('1',preferred_categories);

Above query will give you categories which are having preferred_categories 1 along with or without other categories.In table records might have comma-separated values like ’4,5,7,8′or ’1,11′ or ’1,4,8,11,′ anything. So above expression in WHERE will return value greater than “zero” (0) and that row will be returned in result.

Keep Querying :)

原文地址:  http://www.bytestechnolab.com/blog/2011/12/05/find_in_set-mysql-function-comma-sperated-search/

阅读(1102) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~