Home >Database >Mysql Tutorial >How to Join Tables with Comma-Separated Join Fields?
Joining Tables with Comma-Separated Join Fields
In database management, it is often necessary to join tables based on a field that contains multiple comma-separated values. This presents a challenge when performing queries that exclude the join field and instead select matching values from the related table.
In this scenario, we have two tables, categories and movies, where the categories column in the movies table contains a comma-separated list of category IDs. Our goal is to perform a query that retrieves the categories for each movie in an array format.
Solution
One way to achieve this is by using the JOIN operation with a subquery that utilizes the find_in_set() function. The find_in_set() function checks if a specified value exists within a comma-separated string.
The following query demonstrates how to join the movies and categories tables based on the comma-separated category IDs:
select m.id, group_concat(c.name) from movies m join categories c on find_in_set(c.id, m.categories) group by m.id
Explanation
Output
The output of the query is a table with two columns: id (the movie ID) and categories (an array of category names). For instance, the output might look like this:
id | categories |
---|---|
1 | Comedy,Drama |
2 | Action,Drama |
4 | Other,Dance |
The above is the detailed content of How to Join Tables with Comma-Separated Join Fields?. For more information, please follow other related articles on the PHP Chinese website!