我有3张桌子
admin_courses
ImageView
Admin_course_groups
c_id | c_name | c_status
1 | test1 | 1
2 |test2 |1
3 |test3 |1
4 test4 1
这里总共添加了四门课程,我想知道为每个用户分配了多少门课程,我有查询
a_id | fk_c_id |fk_g_id |start_date |end_date
1 | 1 | 1 | 2018-10-10 |2018-10-20
2 | 5 |1 | 2018-10-10 | 2018-10-20
3 | 4 |3 |2018-10-10 |2018-10-20
Group_permision
gp_id|fk_g_id|user_id
1 1 2
2 3 2
2 1 3
因此,这里将返回所有课程,如果为用户COUNT(SELECT c_id
, c_name
, COUNT(a_id) AS nam
, MIN(start_date) as start_date
, MIN(end_date) as end_date
FROM admin_courses c
LEFT
JOIN Admin_course_groups g
ON g.fk_c_id = c.c_id
left
join Group_permision h
on g. fk_g_id=h.fk_g_id
and users_id=3
where c.c_status=1
GROUP
BY c_id
)分配了课程,将返回1,否则返回0。
现在我的问题是,如果users_id是3,则用户只分配了1门课程,但我得到了3个而不是1个。
请帮我。任何帮助将不胜感激。
答案 0 :(得分:1)
user_id
;另外,请使用Count(Distinct ...)
避免多次计算同一用户。c.c_name
子句中添加了Group By
,以与only_full_group_by
模式兼容。阅读:SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by user_id
,即可计算用户总数。它会限制您的数据。尝试:
SELECT c.c_id
, c.c_name
, COUNT(DISTINCT h.user_id) AS nam
, MIN(g.start_date) AS start_date
, MIN(g.end_date) AS end_date
FROM admin_courses AS c
LEFT
JOIN Admin_course_groups AS g
ON g.fk_c_id = c.c_id
LEFT
JOIN Group_permision AS h
on g.fk_g_id = h.fk_g_id
WHERE c.c_status=1
GROUP
BY c.c_id,
c.c_name
答案 1 :(得分:0)
您的问题缺少一些关键信息,但是如果我正确理解了该问题,我只会尝试将Distinct
添加到计数中:
SELECT `c_id`, `c_name`, COUNT(distinct `a_id`)
....