我的查询
SELECT * FROM semesters WHERE student_id = 434 AND marks_id <= 576 AND semester_id <= 2345
我有一个表“学期”我在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,我想用逗号分隔两个exam_ids和marks_id在单行中。我必须使用GROUP_CONCAT,但我不确定它是如何工作的。提前谢谢。
答案 0 :(得分:0)
将MySQL GROUP_CONCAT
与group by
SELECT *,GROUP_CONCAT(exam_id) as exam_id,GROUP_CONCAT(marks_id)
as marks_id FROM semesters group by semester_id
答案 1 :(得分:0)
1*x + 0*y - 1 = 0
答案 2 :(得分:0)
我会使用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