简体   繁体   中英

How to use in clause in subquery

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?

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
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;

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

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM