我必须将一些数据导出到Excel文件中。此数据来自名为“ tb_Forms”的表,并且在另一个名为“ tb_Movement”的表中具有多重关系,如下所示
+----------+---------------------+ | tb_Forms | | +----------+---------------------+ | FormsId | Description | | 1 | "form 1" | | 2 | "form 2" | | 3 | "form 3" | +----------+---------------------+
+-----------------+---------------+-------------------+--------------+--------+-----------------------+ | tb_Movement | | | | | | +-----------------+---------------+-------------------+--------------+--------+-----------------------+ | MovementId | FirstAnswer | SecondAnswer | ResponseDate | UserFk | FormsFk | | 1 | "Lorem Ipsum" | "dolor sit amet" | 2018-07-31 | 1 | 1 | | 2 | "consectetur" | "adipiscing elit" | 2018-08-01 | 2 | 1 | +-----------------+---------------+-------------------+--------------+--------+-----------------------+
+----------+---------------------+ | tb_Users | | +----------+---------------------+ | UserId | Name | | 1 | João Silva | | 2 | Maria Oliveira | +----------+---------------------+
我想找到一种获得两种结果的方法:
Result First Remark: "Lorem Ipsum", Second Remark: "dolor sit amet" in 2018-07-31 by João Silva First Remark: "consectetur", Second Remark: "adipiscing elit" in 2018-08-01 by Maria Oliveira
但是我只能得到第一个结果(JoãoSilva),仅此而已。 这是我所做的查询:
SELECT GROUP_CONCAT(CONCAT(
"First Remark: ", mv.FirstRemark,
"\rSecond Remark: ", mv.SecondRemark,
"\rin ", mv.ResponseDate, " by ",
(SELECT Name FROM tb_Users WHERE UserId = mv.UserFk)
) SEPARATOR ',')
FROM tb_Movement mv
WHERE mv.FormsFk = 1;
我已经尝试过
SET SESSION group_concat_max_len = 1000000;
..因为“备注”字段可能非常大,但这似乎不是解决方案。
我必须像这样汇总所有答案,因为每个表单行在Excel中也必须是唯一的行。
答案 0 :(得分:2)
我建议:
SELECT GROUP_CONCAT('First Remark: ', mv.FirstRemark,
'\rSecond Remark: ', mv.SecondRemark,
'\rin ', mv.ResponseDate,
' by ', u.name
SEPARATOR ','
)
FROM tb_Movement mv LEFT JOIN
tb_Users u
ON u.userId = mv.UserFK
WHERE mv.FormsFk = 1;
注意:
GROUP_CONCAT()
处理多个参数,因此CONCAT()
是不必要的。JOIN
。在聚合查询中使用相关子查询会产生意外结果或产生错误-都不是所希望的。LEFT JOIN
更接近您的意图,因此NULL
外键引用不会被过滤掉。