(MySQL) How to tell if a numeric variable is contained in a field in a table, and lists all the data in the table that contains the variable. How to Handle

Source: Internet
Author: User
(MySQL) How to tell if a numeric variable is contained in a field in a table and lists all the data in the table that contains the variable.
This table contains the following fields
ID csite ....
1 1,2,13 ....
2 2,3,4 ....
3 1,4,5 ....
4 2,5,23 ....
5 1,3,8 ....

Suppose you get a number variable 3, how to list all rows of data that contain the number 3

Use Select Id,csite from table where csite like '%3% ' or csite like '%3,% ' or csite like '%,3,% ' or csite like '%,3% '

It's not going to work, you'll find 13,23.

The desired result is:
ID csite ....
2 2,3,4 ....
5 1,3,8 ....

Looked up some information, with this charindex (3,csite) >0 tried no matter what to do??

Don't be too complicated SQL statements and stored procedures

Thank you!!!!!



------Solution--------------------
You can use MySQL's own function find_in_set

Find_in_set (Str,strlist)
Returns a value if the string str is in the list strlist consisting of n substrings, returns a 1 to N. A list of strings is made up of multiple substrings separated by the character ",". If the first argument is a constant string, and the second argument is a set column type, the Find_in_set () function is optimized to use bitwise operations! If STR is not strlist or if Strlist is an empty string, the return value is 0. If either parameter is NULL, the return value is also null. If the first parameter contains a ",", this function will not work at all:
mysql> SELECT find_in_set (' B ', ' a,b,c,d ');
2

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.