我正在尝试编写一个查询来告诉我每种颜色的数量Female
。
White - 2
Blue - 5
Green - 13
到目前为止,我有以下查询,其中一些尝试已被注释掉:
SELECT a.id AS aid, af.field_name AS aname, afv.field_value
FROM applications app, applicants a, application_fields af, application_fields_values afv, templates t, template_fields tf
WHERE a.application_id = app.id
AND af.application_id = app.id
AND afv.applicant_id = a.id
AND afv.application_field_id = af.id
#AND af.template_id = t.id
AND af.template_field_id = tf.id
AND t.id = tf.template_id
AND afv.created_at >= '2013-01-01'
AND afv.created_at <= '2013-12-31'
#AND af.field_name = 'Male'
AND afv.field_value = 1
ORDER BY aid, aname
#GROUP BY aid, aNAME
#HAVING aname = 'Female';
目前,此查询返回如下数据:
aid | aname | field_value
4 Female 1
4 White 1
5 Green 1
5 Female 1
6 Female 1
6 White 1
7 Blue 1
7 Female 1
8 Female 1
8 Blue 1
9 Male 1
9 Green 1
表结构:
applications:
id
application_fields:
id
application_id
field_name
applications_fields_values:
id
application_field_id
applicant_id
field_value
template:
id
template_fields:
id
template_id
applicant:
id
application_id
样本数据:
application_fields
id | application_id | field_name |template_id | template_field_id
1 | 1 | blue | 1 | 1
2 | 1 | green | 1 | 2
3 | 1 | female | 1 | 3
application_fields_values
id | application_field_id | applicant_id | field_value
4 | 1 | 1 | 1
5 | 2 | 1 | 0
6 | 3 | 1 | 1
templates
id | name |
1 | mytemplate |
template_fields
id | template_id | field_name |
1 | 1 | blue
2 | 1 | green
3 | 1 | female
编辑
我很确定下面的查询得到了我正在寻找的东西,但是它非常慢,而且我最大的表的行数少于 30K。
询问
SELECT af.field_name AS aname, sum(afv.field_value) AS totals
FROM applications app, applicants a, application_fields af, application_fields_values afv, templates t, template_fields tf
WHERE a.application_id = app.id
AND af.application_id = app.id
AND afv.applicant_id = a.id
AND afv.application_field_id = af.id
AND af.template_field_id = tf.id
AND t.id = tf.template_id
AND afv.created_at >= '2013-01-01'
AND afv.created_at <= '2013-12-31'
AND afv.field_value = 1
AND a.id IN (
SELECT
a2.id
FROM applications app2, applicants a2, application_fields af2, application_fields_values afv2, templates t2, template_fields tf2
WHERE af2.application_id = app2.id
AND afv2.applicant_id = a2.id
AND afv2.application_field_id = af2.id
AND af2.template_field_id = tf2.id
AND t2.id = tf2.template_id
AND afv2.created_at >= '2013-01-01'
AND afv2.created_at <= '2013-12-31'
#AND af2.field_name = 'Male'
AND af2.field_name = 'Female'
AND afv2.field_value = 1
)
GROUP BY aname;
产生结果:
aname | totals
Green 2
Black 27
Blue 5