1

我有这个 SQL 查询:

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    c.telephone as telephone,
    c.email as email,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE 
    c.id_customer = 2
FOR JSON PATH

SELECT * FROM Customer WHERE ID_CUSTOMER = 2
SELECT * FROM User WHERE ID_Customer = 2

此查询返回此 JSON:

[
    { 
      "name": "blablabla",
      "social": "123123123",
      "telephone": "91123123",
      "email": "blabla@gmail.com",
      "name":"blabla"
    }
]

有没有办法获得如下所示的 JSON:

{
  "name": "blabla",
  "social_number": "123123123",
  "emails": [
    {
      "email": "blabla@gmail.com"
    },
    {
      "email": "blablabla@gmail.com"
    }
  ],
  "telephones": [
    {
      "number": "(604)6622141"
    },
    {
      "number": "(652) 2123223"
    }
  ],

感谢您的帮助!

我对编码和 StackOverflow 还是很陌生……对于任何错误,我深表歉意!

4

1 回答 1

1

您可以使用相关的子查询,FOR JSON在每个

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    telephones = (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
    ),
    emails = (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
    ),
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE 
    c.id_customer = 2
FOR JSON PATH;

您也可以将其作为APPLY

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    t.telephones,
    e.emails,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
OUTER APPLY (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
) t(telephones)
OUTER APPLY (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
) e(emails)
WHERE 
    c.id_customer = 2
FOR JSON PATH;
于 2022-02-08T14:51:26.557 回答