Home >Database >Mysql Tutorial >How to Join Two Tables with Comma-Separated Values Using SQL?
Problem Statement
Database normalization can greatly enhance data management, but sometimes structural limitations prevent implementation. This question explores a method to associate comma-separated values in one table with values from a second table when normalization is not an option.
Solution
In the provided scenario, we aim to combine the values in the 'forDepts' column of the Notes table with their corresponding names from the Positions table. The expected output is a list of note IDs ('nid') with the associated department names concatenated and separated by commas.
To achieve this, we can utilize the FIND_IN_SET() function and the GROUP_CONCAT() function. Here's the SQL query:
SELECT a.nid, GROUP_CONCAT(b.name ORDER BY b.id) DepartmentName FROM Notes a INNER JOIN Positions b ON FIND_IN_SET(b.id, a.forDepts) > 0 GROUP BY a.nid
Explanation
Additional Notes
The provided PHP code appears to output only the first value from the 'forDepts' column. This is likely due to the LEFT JOIN used in the query. To retrieve all values, consider using an INNER JOIN instead.
This approach can be applied in situations where data is stored in a comma-separated format and you need to associate it with other values without restructuring the database.
The above is the detailed content of How to Join Two Tables with Comma-Separated Values Using SQL?. For more information, please follow other related articles on the PHP Chinese website!