Reputation: 1001
I have two tables like follows,
Table1:
ID NAME
------ --------
IM-1 Pencil
IM-2 Pen
IM-3 NoteBook
IM-4 Eraser
TABLE-2:
ID ITEM_ID
------ --------------
MT-1 IM-1
MT-2 IM-1,IM-2,IM-3
MT-3 IM-1,IM-2,IM-4
Required Result is :
ID ITEMNAME
------ --------
MT-1 Pencil
MT-2 Pencil,Pen,NoteBook
MT-3 Pencil,Pen,Eraser
But by using the query
SELECT T2.ID,
(SELECT T1.NAME
FROM TABLE1 AS T1
WHERE T1.ID IN (T2.ITEM_ID)) AS ITEMNAME
FROM TABLE2 AS T2
I get the result:
ID ITEMNAME
------ --------
MT-1 Pencil
MT-2 (NULL)
MT-3 (NULL)
Can anyone help me pls?
Upvotes: 1
Views: 314
Reputation: 71
what you are looking for is a recursive way to fetch the names of the items from a list of items.
it need to be done using a scripting language in a program.. sql doesn't support such way of fetching data..
you need to load the list of values in a string then split them then replace them with their values in the database..
Upvotes: 0
Reputation: 435
SELECT T2.ID, T1.NAME as ITEMNAME
FROM TABLE2 AS T2 LEFT JOIN TABLE1 AS T1 ON
FIND_IN_SET(T1.ID,T2.ITEM_ID)>0 AND FIND_IN_SET(T1.ID,T2.ITEM_ID) IS NOT null;
Upvotes: 0
Reputation: 263683
try this:
SELECT b.ID,
GROUP_CONCAT(a.Name) as ItemName
FROM Table2 b INNER JOIN Table1 a
ON FIND_IN_SET(a.name, b.Item_ID)
GROUP BY b.ID
Upvotes: 0
Reputation: 52645
Without normalizing you can try this. But this query won't be SARGable, and as ypercube pointed out storing a comma separated list in a db is a bad idea.
SELECT T2.ID,
GROUP_CONCAT(T1.NAME SEPARATOR ',')
FROM TABLE2 AS T2
INNER JOIN TABLE2 AS T1
ON FIND_IN_SET (T1.ID , T2.ITEM_ID )
GROUP BY
T2.ID
Upvotes: 1