gpt4 book ai didi

python - 将平面查询结果转换为更定义的表结构

转载 作者:行者123 更新时间:2023-11-29 15:20:48 25 4
gpt4 key购买 nike

我正在使用 Flask 和 mysql 为我的一个简单应用程序创建 API。我不太确定如何将连接到具有一对多关系的表的平面查询结果转换为表结构的 json 对象。

这是我想要执行的查询的示例。每个食谱可能有很多方向和很多成分。

SELECT r.id
, r.name
, r.description
, rd.text
, ri.name
, ri.amount
FROM recipes r
LEFT JOIN recipe_directions rd ON rd.recipe_id = r.id
LEFT JOIN recipe_ingredients ri ON ri.recipe_id = r.id

我想将此查询的平面结果转换为如下所示的 json 对象。 mysql 连接器或 flask 中是否已经有一些东西可以用来完成此任务?

[{
id: 1,
name: 'Recipe 1',
description: '...',
directions: [{
text: 'Cook the rice'
},
{
text: 'Do the next step...'
}],
ingredients: [{
name: 'Rice',
amount: '1 cup'
},
{
name: 'Onion',
amount: '1'
}]
},
{
id: 2,
name: 'Recipe 2',
description: '...',
directions: [...]
ingredients: [...]
}]

最佳答案

您正在寻找的是GROUP_CONCAT() function 。这将允许您从每个返回行的连接表中返回多条记录。您仍然需要进行一些格式化,但这将允许您将每个食谱作为一条记录返回,并包含其说明和成分。

您可能还想考虑使用像 records 这样的包使用它的 .as_dict() 函数可以让事情变得更容易一些。

关于python - 将平面查询结果转换为更定义的表结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59385703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com