gpt4 book ai didi

MySQL如何通过外键id选择多行?

转载 作者:行者123 更新时间:2023-12-05 05:41:46 24 4
gpt4 key购买 nike

调查表: enter image description here

问题表: enter image description here

我的 sql 查询:

SELECT s.id, q.questionFROM questions qJOIN surveys s ON q.surveyId = s.id;

我的结果:

[
{
"id": 5,
"question": "Which industry are you working at?"
},
{
"id": 5,
"question": "What is your company's highest annual revenue?"
},
{
"id": 5,
"question": "How long has your company been operated? updated"
}
]

但我想要这样的输出:

[
{
"id": 5,
"questions": [
"Which industry are you working at?",
"What is your company's highest annual revenue?",
"How long has your company been operated?"
]
}
]

enter image description here

最佳答案

你想要的是一个GROUP BY

SELECT 
s.id,
JSON_ARRAYAGG(q.question)
FROM
questions q
JOIN
surveys s ON q.surveyId = s.id;
GROUP BY
s.id

这可能会非常接近您想要的,但是您需要 MySQL 8.0.14 或更高版本。看看JSON_ARRAYAGG() .可以使用其他聚合函数,但您需要对结果做一些处理。

不过,GROUP BY 是必不可少的。

关于MySQL如何通过外键id选择多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72239516/

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