我正在处理以下查询而无法找出一件事。底部主查询的结果如下: -
Institute name || Total users || Students || teachers || professionals || Email || Country of Teacher.**
我想将该国的研究所添加为第二栏。 表名 - 国家 主键 - Id
查询很容易理解。我应该如何处理或容纳以下查询到我能得到最终结果的大问题: -
Institute name || Country name of institute || Total users || Students || teachers || professionals || Email || Country of Teacher.**
select pl.name AS institute_name, c.name as country_name
from profiles p , places pl , countries c
where pl.id = p.place_id and p.country_id = c.id
and pl.formatted_address != ''
//主查询从这里开始
SELECT t.institute_name, SUM(t.total_users), SUM(t.students), SUM(t.teachers), SUM(t.professionals), MAX(t.teacher_emails), MAX(t.teacher_countries)
FROM
((SELECT pl.name AS institute_name, COUNT(ut.classification) AS total_users, COUNT(ut.classification) AS students, 0 AS teachers, 0 AS professionals, NULL AS teacher_emails, NULL AS teacher_countries
FROM profiles p , places pl , countries c ,user_types ut, users u
WHERE pl.id = p.place_id AND
ut.classification = 'student' AND
p.country_id = c.id AND
p.user_type_id = ut.id
AND p.user_id = u.id
AND DATE(u.created_at) >= '2015-10-02 08:00:00'
AND formatted_address != ''
GROUP BY pl.name, ut.classification)
) AS t
GROUP BY t.institute_name
HAVING SUM(t.total_users) >= '10'
ORDER BY t.total_users DESC
答案 0 :(得分:0)
试试这个
SELECT t.institute_name, t.country_name, SUM(t.total_users), SUM(t.students), SUM(t.teachers), SUM(t.professionals), MAX(t.teacher_emails), MAX(t.teacher_countries)
FROM
((SELECT pl.name AS institute_name, c.name as country_name, COUNT(ut.classification) AS total_users, COUNT(ut.classification) AS students, 0 AS teachers, 0 AS professionals, NULL AS teacher_emails, NULL AS teacher_countries
FROM profiles p , places pl , countries c ,user_types ut, users u
WHERE pl.id = p.place_id AND
ut.classification = 'student' AND
p.country_id = c.id AND
p.user_type_id = ut.id
AND p.user_id = u.id
AND DATE(u.created_at) >= '2015-10-02 08:00:00'
AND formatted_address != ''
GROUP BY pl.name, ut.classification)
) AS t
GROUP BY t.institute_name
HAVING SUM(t.total_users) >= '10'
ORDER BY t.total_users DESC