Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using sql server 2008 r2 with php in my website. I have 2 tables.

1 is for employees.

(int)      (nvarchar)   (nvarchar)

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

2 is for work

(int)      (nvarchar)   (nvarchar)

workid      name        employees
  1         task1       1,3
  2         task2       2,3
  3         task3       1,3,4
  4         task4         2

I want to make query which give me work description with employee name where type < 3.

Means i want to get result like this.

workid       name       employee
  1          task1      john, leah
  2          task2      peter, leah
  3          task3      john,leah,frank

like wise

so how can i achieve this result with sql query ?

I can not change in table schema.

i tried to use with case when statement but its not working.

Please help me to get this working..

like image 407
Mausami Avatar asked Nov 23 '25 02:11

Mausami


1 Answers

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
  • SQLFiddle Demo
like image 161
John Woo Avatar answered Nov 24 '25 23:11

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!