mysql的Group问题

时间:2018-09-21 05:18:30

标签: mysql

我有一个查询

return $this->db->select ("SELECT `c_id`,`c_name`,(select count(`a_id`) nam from Admin_course_groups where fk_c_id = `c_id` and fk_g_id = $id)adm from admin_courses");

并输出:

Array
(
    [0] => Array
        (
            [c_id] => 1
            [c_name] => Java - Basic Operators
            [adm] => 1
        )

    [1] => Array
        (
            [c_id] => 3
            [c_name] => JAVA Questions and Answers
            [adm] => 0
        )

    [2] => Array
        (
            [c_id] => 4
            [c_name] => Java - Collections Framework
            [adm] => 0
        )

)

所以我想从此查询中获取开始日期和结束日期。所以我尝试了

 return $this->db->select ("SELECT `c_id`,`c_name`,count(`a_id`) nam,start_date,end_date from admin_courses join Admin_course_groups on  fk_c_id = `c_id` where fk_g_id = $id group by `a_id`");

仅返回一个结果

Array
(
    [0] => Array
        (


[c_id] => 1
            [c_name] => Java - Basic Operators
            [nam] => 1
            [start_date] => 2018-01-01
            [end_date] => 2018-09-25
        )

)

预期产量

 Array
    (
        [0] => Array
            (
                [c_id] => 1
                [c_name] => Java - Basic Operators
                [nam] => 1
                [start_date] => 2018-01-01
                [end_date] => 2018-09-25
            )

        [1] => Array
            (
                [c_id] => 3
                [c_name] => JAVA Questions and Answers
                [adm] => 0
                [start_date] =>
                [end_date] =>
            )

        [2] => Array
            (
                [c_id] => 4
                [c_name] => Java - Collections Framework
                [adm] => 0
                [start_date] => 
                [end_date] => 
            )

    )

admin_courses

c_id      |     C_name           |         C_desc | C_status
1           Java - Basic Operators        test        1
2          JAVA Questions and Answers     test2       1
3          Java - Collections Framework   test3        1

Admin_course_groups

a_id | fk_c_id |fk_g_id|start_date|end_date
 1      1          2      2018-01-01 2018-09-25

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您的查询存在一些问题,导致其未返回所需的所有结果。首先,您正在使用JOIN,并且admin_course_groups中只有一行匹配行,因此将您限制为一行。您应该改用LEFT JOIN。其次,当您应按a_id分组时,您正在按c_id分组。最后,在更改为LEFT JOIN之后,您将需要修改WHERE子句以使fk_g_id成为NULL。此查询应提供您想要的结果:

SELECT `c_id`, `c_name`, COUNT(`a_id`) AS nam, MIN(start_date), MIN(end_date)
FROM admin_courses c
LEFT JOIN admin_course_groups g
ON g.fk_c_id = c.`c_id` 
WHERE fk_g_id = 2 OR fk_g_id IS NULL
GROUP BY `c_id`

输出:

c_id    c_name                          nam     start_date  end_date
1       Java - Basic Operators          1       2018-01-01  2018-09-25
2       JAVA Questions and Answers      0       (null)      (null)
3       Java - Collections Framework    0       (null)      (null)

SQLFiddle Demo