how to get name from another table with matching id in another table?

被刻印的时光 ゝ 提交于 2019-12-01 00:21:23

The content of this doesn't totally answers the question but it will suggest on how you can properly normalize the table in order for theproblem to be simplified.

This is a Many-to-Many Relationship.

Employees
- ID (Primary Key)
- Name
- Type

Task
- ID (Primary Key)
- Name

Work
- EmployeeID (Foreign Key)
- TaskID (Foreign Key)

EMPLOYEE TABLE

id         name        type
 1         john         2
 2         peter        1
 3         leah         2
 4         frank        1
 5         tang         3

TASK TABLE

 id         name        
  1         task1       
  2         task2       
  3         task3       
  4         task4  

WORK TABLE

TaskID  EmployeeID
1           1
1           3
2           2
2           4
3           1
3           2
3           3
4           4

Query,

SELECT  t.ID, t.Name,
        STUFF(
        (SELECT ',' + b.Name
        FROM    Work a
                INNER JOIN Employee b
                    ON a.EmployeeID = b.ID
        WHERE   a.TaskID = t.ID 
        FOR XML PATH (''))
        , 1, 1, '')  AS NamesList
FROM    Task t
-- WHERE    ..... -- add additional conditions...
GROUP   BY t.ID, t.Name

Here's one way you can split a comma delimited list using For XML:

SELECT w.workid, w.name, 
  STUFF((
   SELECT ',' +  E.Name AS [text()]
    FROM  (
      SELECT A.workid,  
      Split.a.value('.', 'VARCHAR(100)') AS EmpId
      FROM  
      (SELECT workid,  
       CAST ('<M>' + REPLACE(employees, ',', '</M><M>') + '</M>' AS XML) AS String  
       FROM  work
      ) AS A 
      CROSS APPLY String.nodes ('/M') AS Split(a)
    ) A 
    JOIN employees E ON A.EmpId = E.Id
    WHERE WorkId = w.WorkId
    FOR XML PATH('')
  ), 1, 1, '') AS Employees
FROM work w

SQL Fiddle Demo

This results in:

WORKID   NAME    EMPLOYEES
1        task1   john,leah
2        task2   peter,leah
3        task3   john,leah,frank
4        task4   peter
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!