Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql join two table with comma separated ids

Tags:

sql

mysql

I have two tables

Table 1

ID     NAME
1      Person1
2      Person2
3      Person3

Table 2

ID     GROUP_ID
1      1
2      2,3

The IDs in all the columns above refer to the same ID (Example - a Department)

My Expected output (by joining both the tables)

GROUP_ID     NAME
1            Person1
2,3          Person2,Person3

Is there a query with which i can achieve this. Your help is highly appreciated. Thank you.

like image 546
user2442377 Avatar asked Jun 04 '13 03:06

user2442377


2 Answers

You can use FIND_IN_SET() and GROUP_CONCAT() on this,

SELECT  b.Group_ID, GROUP_CONCAT(a.name) name
FROM    Table2 b
        INNER JOIN Table1 a
            ON FIND_IN_SET(a.ID, b.Group_ID) > 0
GROUP   BY b.Group_ID
  • SQLFiddle Demo
  • MySQL FIND_IN_SET
  • MySQL GROUP_CONCAT()

OUTPUT

╔══════════╦═════════════════╗
║ GROUP_ID ║      NAME       ║
╠══════════╬═════════════════╣
║ 1        ║ Person1         ║
║ 2,3      ║ Person2,Person3 ║
╚══════════╩═════════════════╝

As a sidenote, this query might not perform efficiently as expected. Please do normalize your table properly by not saving values separated by a comma.

UPDATE

GROUP_ID is pretty much confusing. Isn't it PersonIDList? Anyway, here's my suggested schema design:

PERSON Table

  • PersonID (PK)
  • PersonName
  • other columns..

GROUP Table

  • GroupID (PK)
  • GroupName
  • other columns..

PERSON_GROUP Table

  • PersonID (FK) (at the same time PK with column GroupID)
  • GroupID (FK)
like image 119
John Woo Avatar answered Oct 01 '22 00:10

John Woo


I like the FIND_IN_SET option since you are using MySQL, but here is an alternative solution that works as well using LIKE in the JOIN:

select t2.group_id, group_concat(t1.name order by t1.name separator ',' ) name
from t1 inner join t2 
  on concat(',',t2.group_id,',') like concat('%,',t1.id,',%') 
group by t2.group_id;

SQL Fiddle Demo

I would suggest you look into normalizing your data -- storing a comma delimited list in a relational database is usually a bad idea.

like image 37
sgeddes Avatar answered Oct 01 '22 00:10

sgeddes