我正在尝试使用相关表来构建数据库。我从数据库中获得了正确的输出,但是-由于用户相同,并且数据唯一的变化是课程,因此我想将值“ Engelsk”和“ Matematik”收集在同一行中,而不是除了课程外,具有两个几乎相同的输出。
如果不在数据库的同一行中,甚至可以做到这一点?如果是这样,我非常想知道如何:)

Array
(
[0] => Array
    (
        [Type] => Elev
        [Username] => test
        [Name] => Test Testsen
        [Grade] => 9. Klasse
        [Course] => Engelsk
    )

[1] => Array
    (
        [Type] => Elev
        [Username] => test
        [Name] => Test Testsen
        [Grade] => 9. Klasse
        [Course] => Matematik
    )

)


所以基本上我想要实现的是这样的:

Array
(
[0] => Array
(
    [Type] => Elev
    [Username] => test
    [Name] => Test Testsen
    [Grade] => 9. Klasse
    [Course] => Engelsk, Matematik
)


我的查询如下所示:

                SELECT
                *
            FROM
                lek_Essentials
            LEFT JOIN
                lek_Type
            ON
                lek_Essentials.TypeId = lek_Type.TypeId
            LEFT JOIN
                lek_Grades
            ON
                lek_Essentials.GradeId = lek_Grades.GradeId
            LEFT JOIN
                lek_GradeCourses
            ON
                lek_Grades.GradeId = lek_GradeCourses.GradeId
            LEFT JOIN
                lek_Courses
            ON
                lek_GradeCourses.CourseId = lek_Courses.CourseId
            LEFT JOIN
                lek_Request
            ON
                lek_Courses.CourseId = lek_Request.CourseId
            WHERE
                lek_Essentials.UserId = lek_Request.UserId

最佳答案

尚不清楚数组中各列来自哪个表,但是在MySQL中,您可以使用GROUP_CONCAT将两行汇总为一个:

SELECT t.type,
  e.username,
  e.name,
  g.grade,
  group_concat(c.course) course
FROM lek_Essentials e
LEFT JOIN lek_Type t
  ON e.TypeId = t.TypeId
LEFT JOIN lek_Grades g
  ON e.GradeId = g.GradeId
LEFT JOIN lek_GradeCourses gc
  ON g.GradeId = gc.GradeId
LEFT JOIN lek_Courses c
  ON gc.CourseId = c.CourseId
LEFT JOIN lek_Request r
  ON c.CourseId = r.CourseId
WHERE e.UserId = r.UserId
group by t.type, e.username, e.name, g.grade

关于php - 使用相关表在1行中收集信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16668437/

10-13 02:09