MySQL如何将表作为子数组连接?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL如何将表作为子数组连接?相关的知识,希望对你有一定的参考价值。
所以我有两个表,我想运行一个查询,该查询将连接Receipt
表和Receipt_Item
表,以便Receipt_Item
表是如下所示的子数组。
Receipts -
| receipt_id | phone | amount | status |
|------------|------------|--------|---------|
| 1 | 7777777777 | 5682 | Success |
| 2 | 8888888888 | 4586 | Success |
| 3 | 5555555555 | 7589 | Success |
Receipt_Item -
| receipt_id | item_id | quantity | price |
|------------|---------|----------|-------|
| 1 | 1 | 23 | 5682 |
| 1 | 2 | 30 | 5682 |
| 2 | 1 | 10 | 7589 |
| 3 | 1 | 23 | 4355 |
| 3 | 2 | 41 | 3665 |
预期输出-
[
"receipt_id": 1,
"phone": "7777777777",
"amount": "5682",
"status": "Success",
"receipt_item" : [
"receipt_id" : 1,
"item_id" : 1,
"quantity" : 23,
"price" : 5682
,
"receipt_id" : 1,
"item_id" : 2,
"quantity" : 30,
"price" : 5682
]
,
"receipt_id": 2,
"phone": "8888888888",
"amount": "4586",
"status": "Success",
"receipt_item" : [
"receipt_id" : 2,
"item_id" : 1,
"quantity" : 10,
"price" : 7589
]
,
"receipt_id": 3,
"phone": "5555555555",
"amount": "7589",
"status": "Success",
"receipt_item" : [
"receipt_id" : 3,
"item_id" : 1,
"quantity" : 23,
"price" : 4355
,
"receipt_id" : 3,
"item_id" : 2,
"quantity" : 41,
"price" : 3665
]
]
谢谢你。
答案
您可以使用JSON_ARRAYAGG和JSON_OBJECT函数来实现。我认为这是您需要的:
SELECT JSON_ARRAYAGG(JSON_OBJECT('receipt_id', R.receipt_id, 'phone', R.phone, 'amount', R.amount, 'status', R.status, 'receipt_Item', I.Item))
from Receipts R
LEFT JOIN
(SELECT receipt_id, JSON_ARRAYAGG(JSON_OBJECT('receipt_id', receipt_id, 'item_id', item_id, 'quantity', quantity, 'price', price)) AS Item from ReceiptItem Group BY receipt_id) I ON R.receipt_id = I.receipt_id
可以找到[DBFiddler示例here
以上是关于MySQL如何将表作为子数组连接?的主要内容,如果未能解决你的问题,请参考以下文章