Home >Database >Mysql Tutorial >How to Join Tables with Comma-Separated Value Fields in SQL?
Querying Multiple Join Fields with Comma-Separated Values
In SQL, when dealing with tables containing comma-separated-lists (CSVs) in their fields, it can be challenging to perform joins effectively. This article explores a specific scenario where the categories column in a movies table contains multiple category IDs, and the goal is to exclude it entirely while fetching the corresponding category names from a categories table.
The following tables illustrate the scenario:
Table categories: -id- -name- 1 Action 2 Comedy 4 Drama 5 Dance Table movies: -id- -categories- 1 2,4 2 1,4 4 3,5
To perform the desired join, we can utilize the find_in_set() function in conjunction with a group_concat() operation. Here's the query:
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
Query Explanation:
The resulting output displays the movie IDs along with their corresponding category names in an array format. This allows for easy access to the relevant categories without the need to decode the CSV in the movies table.
The above is the detailed content of How to Join Tables with Comma-Separated Value Fields in SQL?. For more information, please follow other related articles on the PHP Chinese website!