我有以下两个表:
+----------------------------+ | Parent Table | +----------------------------+ | uuid (PK) | | caseId | | param | +----------------------------+ +----------------------------+ | Child Table | +----------------------------+ | uuid (PK) | | parentUuid (FK) | +----------------------------+
我的目标是进行(左?)连接,并根据父行上的数组中的 FK 获取子表中的所有匹配行,而不是匹配列名上的父行本身(请参阅所需输出的进一步下方) .
表中的值示例:
父表:
1. uuid: "10dd617-083-e5b5-044b-d427de84651", caseId: 1, param: "test1" 2. uuid: "5481da7-8b7-22db-d326-b6a0a858ae2f", caseId: 1, param: "test1" 3. uuid: "857dec3-aa3-1141-b8bf-d3a8a3ad28a7", caseId: 2, param: "test1"
子表:
1. uuid: 7eafab9f-5265-4ba6-bb69-90300149a87d, parentUuid: 10dd617-083-e5b5-044b-d427de84651 2. uuid: f1afb366-2a6b-4cfc-917b-0794af7ade85, parentUuid: 10dd617-083-e5b5-044b-d427de84651
我想要的输出应该是什么样子:
像这样的查询(使用伪 SQL 代码):
SELECT * FROM Parent_table WHERE caseId = '1' LEFT JOIN Child_table ON Child_table.parentUuid = Parent_table.uuid
期望的输出(JSON)
[ { "uuid": "10dd617-083-e5b5-044b-d427de84651", "caseId": "1", // DESIRED FORMAT HERE "childRows": [ { "uuid": "7eafab9f-5265-4ba6-bb69-90300149a87d", "parentUuid": "10dd617-083-e5b5-044b-d427de84651" }, { "uuid": "f1afb366-2a6b-4cfc-917b-0794af7ade85", "parentUuid": "10dd617-083-e5b5-044b-d427de84651" } ] }, { "uuid": "5481da7-8b7-22db-d326-b6a0a858ae2f", "caseId": "1" } ]
sqljsonsql服务器加入左连接
您可以使用嵌套FOR JSON子句来实现这一点。
FOR JSON
SELECT p.uuid, p.caseId, childRows = ( SELECT c.uuid, c.parentUuid FROM Child_table c WHERE c.parentUuid = p.uuid FOR JSON PATH ) FROM Parent_table p WHERE p.caseId = '1' FOR JSON PATH;