使用相关表收集1行信息

时间:2013-05-21 11:02:57

标签: php mysql database

我正在尝试使用相关表格构建我的数据库。我从数据库中得到正确的输出,但是 - 由于用户是相同的,并且数据的唯一变化是课程,我想在同一行收集值“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

1 个答案:

答案 0 :(得分:1)

不清楚数组中每个列的哪些表来自哪些表,但在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