如果我使用此查询:
SELECT clinic.id
FROM clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active'
AND clinic.status = 'Approved'
AND user.role_id = 2
GROUP BY clinic.id;
所以它给了我所有的行像
32
35
36
42
44
47
50
错误如果我要获得结果的总数,那么我应用查询:
SELECT count(clinic.id) AS cnt
FROM clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active'
AND clinic.status = 'Approved'
AND user.role_id = 2
GROUP BY clinic.id;
我刚刚将count()应用于id,然后返回
1
1
1
1
1
1
1
它不返回7,我想要结果为7。 请有人指导。
答案 0 :(得分:5)
请勿使用GROUP BY 或尝试此
SELECT clinicID,SUM(case when clinic !=null then 1 ELSE NULL END).id AS cnt
FROM clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active'
AND clinic.status = 'Approved'
AND user.role_id = 2
GROUP BY clinic.id;
答案 1 :(得分:2)
我可以看到两个选择。由于您正在进行分组,因此您将获得每组的计数,这是预期的行为。要获得总计数,您需要删除group by
并执行此操作:
SELECT count(distinct clinic.id)
FROM clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active'
AND clinic.status = 'Approved'
AND user.role_id = 2
或者只是在新查询中使用您的第一个查询作为子查询,如下所示:
select count(*) from (
SELECT clinic.id
FROM clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active'
AND clinic.status = 'Approved'
AND user.role_id = 2
GROUP BY clinic.id) q
答案 2 :(得分:2)
SELECT count(clinic.id) AS cnt
FROM
clinic
JOIN dentist ON dentist.id = clinic.dentist_id
JOIN user ON user.id = dentist.user_id
WHERE user.status = 'Active' AND clinic.status = 'Approved' AND user.role_id = 2
删除GROUP BY子句。