Find a certain number inside a mysql string

0

Good morning everyone. I have a question that I can not solve.

In a given table of a BD I have a column that saves a string as follows:

  

1,2,3,4,5 Line 1
  11.22,33,44,55 Line 2

Now you need to do a search to select only rows that have a given number eg:

Select column X where it contains the number 2

I tried the search using the code below, but it is returning me both line 1 and line 2, however I only needed line 1 which is where it has exactly the number 2 and not the line where it has the number 22

$sql = 'SELECT 'ativos' from 'produtos' WHERE 'ativos' LIKE "%'.$id.'%"';

Does anyone have any idea how I can solve this problem? Thanks in advance.

    
asked by anonymous 20.12.2017 / 12:51

3 answers

1

Try using the FIND_IN_SET as follows.

  Assuming your Active field is made up of relationship id's, I've taken the liberty of using an adapted sql where you get an id . Anything alert in the comments whether it serves you or not.

$sql += "SELECT ativos from produtos WHERE FIND_IN_SET(" + $id + ",ativos)"
    
20.12.2017 / 13:08
1

Use the snippet below. It will consider the commas as separators.

$sql = 'SELECT 'ativos' 
from 'produtos'
 /*Separadores no meio da sequência */
WHERE 'ativos' LIKE '%," . $id . ",%' 
 /*Separadores no início da sequência */ 
OR 'ativos' LIKE '" . $id . ",%'  
 /*Separadores no fim da sequência */
OR 'ativos' LIKE '%," . $id . "'  

There must be some other technique that solves your problem in a better way, but this one I believe already does what you want.

    
20.12.2017 / 12:58
0

Good morning, as I understand you need to display only the first line of your search, then change your sql code to:

$sql = 'SELECT 'ativos' from 'produtos' WHERE 'ativos' LIKE "%'.$id.'%" LIMIT '1' DESC';

Note: DESC list by the most recent record and the oldest ASC.

    
20.12.2017 / 13:08