如何在查询中使用两列的 GROUP_CONCAT

how to use GROUP_CONCAT of two columns with query

我的查询是这样的

SELECT * FROM  semesters WHERE student_id = 434 AND marks_id <=  576 AND semester_id <=  2345

我有一个 table "semesters" 我正在使用我的查询在 MySQL 中获取包含以下数据的输出:

id       semester_id       exam_id      student_id   marks_id
1          2344               25            434       255
2          2344               34            434       575 
3          2345               48            434       576

如何通过查询将其转换为以下格式?

 id          semester_id        exam_id      student_id   marks_id
 1             2344              25,34          434       255,575
 2             2345               48            434         576

我想要 semster_id 2344 有两个 exam_ids,我想用逗号 seperated.think 将两个 exam_ids 和 marks_id 合并成一行 我必须使用GROUP_CONCAT,但我不确定如何提前works.Thanks。

使用 MySQL GROUP_CONCATgroup by

SELECT *,GROUP_CONCAT(exam_id) as exam_id,GROUP_CONCAT(marks_id) 
as marks_id FROM  semesters group by semester_id
SELECT GROUP_CONCAT((exam_id) separator ',')
     , GROUP_CONCAT((marks_id) separator ',')
FROM semesters
WHERE student_id = 434
    AND marks_id <=  576
    AND semester_id <=  2345
GROUP BY semester_id;

我会使用 GROUP_CONCAT,但我建议强制排序并处理列中的 NULL 值。这样即使一个为空,考试和分数也应该匹配:-

SELECT semester_id,
    GROUP_CONCAT(IFNULL(exam_id, '') ORDER BY id),
    student_id,
    GROUP_CONCAT(IFNULL(marks_id, '') ORDER BY id)
FROM  semesters 
WHERE student_id = 434 
AND marks_id <=  576 
AND semester_id <=  2345
GROUP BY semester_id, 
        student_id

如果您需要一个顺序 ID,您可能需要使用变量手动创建它:-

SELECT  @cnt:=@cnt + 1 AS id,
        sub0.semester_id,
        sub0.exam_id_out,
        sub0.student_id,
        sub0.marks_id_out
FROM
(
    SELECT semester_id,
        GROUP_CONCAT(IFNULL(exam_id, '') ORDER BY id) AS exam_id_out,
        student_id,
        GROUP_CONCAT(IFNULL(marks_id, '') ORDER BY id) AS marks_id_out
    FROM  semesters 
    WHERE student_id = 434 
    AND marks_id <=  576 
    AND semester_id <=  2345
    GROUP BY semester_id, 
            student_id
    ORDER BY semester_id
) sub0
CROSS JOIN 
(
    SELECT @cnt:=0
) sub1