Actually your table was incorrectly designed. The correct one would be to have a support table with the codes and a link to this table. But if there is no possibility to change the table you can use the following options:
1) DISTINCT + SUBSTRING_INDEX + Support Table
Applying the theory of that answer we have the following query
for the proposed search:
SELECT *
FROM (SELECT DISTINCT t.id,
t.id_busca,
t.players,
TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.players, ',', n.numero), ',', -1)) AS ocorrencia
FROM tabela t
CROSS JOIN numeros n
ORDER BY t.id, n.numero) x
WHERE x.ocorrencia = 2
You can check the execution on SQL Fiddle.
In the above solution we create a support table (called numeros
) with possible positions. Note that the numbers are not the values and yes to the positions and with the CROSS JOIN
with this table we perform the SUBSTRING_INDEX
, thus allowing all positions (separated by a comma) to be covered. Note that I used only 10 numbers in the example, but if there are more possible positions the support table must be filled according to the possibilities (always for more).
1) FIND_IN_SET
Another solution is to use the function FIND_IN_SET
:
SELECT t.id,
t.id_busca,
t.players
FROM tabela t
WHERE FIND_IN_SET(2, t.players)
See working on SQL Fiddle.
References:
"I need to check if a value is in a column in the BD". You can edit the question and show an example of columns with rows? ;)
– girorme
Ready. See if it’s more visible.
– Vitor Leite
You want to know the php way to do this operation or in the same bank?
– girorme
No sample of what you tried? Then your question can be closed as it is not very clear, nor do we know if what you want (where the problem is) is in
sql
,php
, or a mix of the two...– MarceloBoni
I strongly suggest reading: How to create a [MCVE]
– MarceloBoni
Okay, try to understand now.
– Vitor Leite
Yes, and if the column is: 102,201,304,852,214. The line will be selected and there is no 2 only in it.
– Vitor Leite
And if 2 is at the end of the string: 104,201,450,201,2 ?
– Vitor Leite
Why did you delete the answers? kkj.
– Vitor Leite
Because if they didn’t solve your question, they only generated what we call visual pollution =], better delete. As I will do with that comment in a moment.
– MarceloBoni