In relational databases, columns typically hold single values for each row. However, in certain scenarios, you may need to store multiple values within a single column, separated by delimiters such as commas. This can lead to challenges when querying the data, as conventional operators like the equality operator no longer work as expected.
For instance, consider the following table, which stores parent-child relationships:
id name children 1 Roberto Michael,Dia 2 Maria John,Alex 3 Mary Alexandre,Diana
If we attempt to find the parent(s) having a child named "Alex" using the query:
WHERE children = 'Alex'
we will retrieve zero results, even though Alex is a child of Maria. This is because we are looking for an exact match, which is not present due to the multiple values in the children column.
To handle such situations, we need to explore alternative approaches:
Normalize the Schema:
The ideal solution is to normalize the schema and create a separate table for children, with a separate row for each child and a reference to the parent. This would allow for efficient querying based on child names.
Using FIND_IN_SET:
If normalizing the schema is infeasible, you can use the FIND_IN_SET function, which checks if a value exists within a comma-separated list. The query would be:
WHERE FIND_IN_SET('Alex', children)
This would return the parent(s) who have a child named Alex. However, it's important to note that FIND_IN_SET is not the most efficient approach and should be used only if normalization is not viable.
The above is the detailed content of How Can I Query for Multiple Values Stored in a Single Database Column?. For more information, please follow other related articles on the PHP Chinese website!