T-SQL查询多对多

时间:2019-03-03 18:28:02

标签: sql json tsql many-to-many

我有3张桌子:

doctors:
-----------
id
name

language:
-----------
id
name

languageDoctors:
----------------
doctor_id
language_id

我想返回带有医生姓名的JSON,然后返回医生拥有的多种语言。

1 个答案:

答案 0 :(得分:1)

好吧,您可以使用for json path来构造json:

select d.*,
       (select l.name as language
        from doctor_languages dl join
             languages l
             on dl.language_id = l.language_id
        where dl.doctor_id = d.doctor_id
        for json path
       ) as languages
from doctors d;

Here是db <>小提琴。