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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3