Home >Database >Mysql Tutorial >How to Join Tables with Comma-Separated Values in a Column?
Database normalization is crucial for efficient data management, but sometimes, projects may require handling legacy data in non-normalized form. This article explores a technique for joining two tables with comma-separated values in a given column.
Scenario:
Suppose we have two tables:
Notes Table:
Positions Table:
Our goal is to join these tables and associate the forDepts column with values from the Positions table, creating a new column with comma-separated position names.
Solution Using CONCAT_WS:
SELECT n.nid, CONCAT_WS(', ', p.name) AS DepartmentName FROM Notes n JOIN Positions p ON n.forDepts = p.id
However, this approach will only retrieve the first match for each department ID, not all matching departments.
Solution Using FIND_IN_SET:
SELECT a.nid, GROUP_CONCAT(b.name ORDER BY b.id) AS DepartmentName FROM Notes a INNER JOIN Positions b ON FIND_IN_SET(b.id, a.forDepts) > 0 GROUP BY a.nid
The FIND_IN_SET function checks if a value is present in a comma-separated string. By using it in the JOIN condition, we ensure that all matching positions are included. The GROUP_CONCAT function concatenates the retrieved position names, separated by commas.
PHP Code Integration:
The given PHP code can be modified to retrieve the extended DepartmentName column by replacing the query in the mysql_query statement with the suggested solution above. This will allow the code to export the comma-separated position names correctly.
Note:
While it's ideal to normalize databases, handling non-normalized data is sometimes necessary. The techniques discussed in this article provide a solution for efficiently joining tables and aggregating comma-separated values in such scenarios.
The above is the detailed content of How to Join Tables with Comma-Separated Values in a Column?. For more information, please follow other related articles on the PHP Chinese website!