Find an exact text inside an string with MySQL

I have a database table with two columns, one for the ID and another one for Colors. Imagine that I have 3 lines in this table with the following data:

ID: 1 => Colors: Blue; Yellow; Red;
ID: 2 => Colors: Green; GreenYellow; Yellowgreen; Blue;
ID: 3 => Colors: Yellow; Blue;

If I want to make a SQL call to know if there is a register with yellow color (just Yellow, no GreenYellow or Yellowgreen). How can I do it? I´m trying with:

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "%Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 1, 2 and 3

 $statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
 $statement->execute(array(":suscritos" => "%Yellow_"));
 $todos_mis_mensajes = $statement->fetchAll();

IDs results: No result

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "_Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 3

i will begin by reminding you that storing multiple values inside a single column violates First Normal Form and is therefore an anti-pattern i.e. you shouldn’t do it if you can avoid it…

try this –

SELECT * FROM comentarios WHERE ( suscritos LIKE 'Yellow;%' OR suscritos LIKE '% Yellow;' )

remember, this query cannot be improved with an index, and will therefore get slower and slower as the table grows in size

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.