I have three tables as follows:
MasterTable
+----------+-------------+
| MasterId | MasterName |
+----------+-------------+
| 1 | Master 1 |
| 2 | Master 2 |
| 3 | Master 3 |
| 4 | Master 4 |
+----------+-------------+
ChildrenTable
+----------+-------------+
| ChildId | ChildName |
+----------+-------------+
| 1 | Child 1 |
| 2 | Child 2 |
| 3 | Child 3 |
| 4 | Child 4 |
+----------+-------------+
LinkTable
+----------+-----------------------+
| Id | MasterId | ChldId |
+----------+-----------------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 2 |
| 4 | 4 | 3 |
+----------+-----------------------+
One child can be linked with multiple masters and LinkTable contains this detail. I want a query to select the following:
1, 'Child 1', 'Master 1, Master 2', '1,2'
2, 'Child 2', 'Master 2', '2'
3, 'Child 3', 'Master 3', '3'
Is it possible to do without loops or calling additional function, using COALESCE
, STUFF
, recursive CTE
etc?