首页 > 解决方案 > 使用 SQL Server:如何在父子关系中显示数据

问题描述

我有两个这样的表:

掌握

Id       MasterName
---------------------
1        Electronic
2        HomeNeeds

子表

Ch_Id      Ch_Name      Master_Id
-----------------------------------
1          L.G             1
2          Nokia           1
3          WoodLand        2

请帮助我-如何在父子关系中显示数据?

就像在表中一样,它应该显示 Like

Id   Product
---------------
1    Electronic
  (Within This)
   Lg 
   Nokia

我知道加入,但它对我没有帮助

标签: sqlsql-server

解决方案


尝试类似:

SELECT
    M.MasterName,
    STRING_AGG (c.ChildName, ', ') as products,
    M.Id
FROM
    Master AS M
    JOIN
    Child as C
    ON M.Id = C.MasterId
GROUP BY
    M.MasterName,
    M.Id

推荐阅读