我有一个3个MySQL表,我需要从中得到结果,以及:
1. Towns
Fields Towncode and Townname
2. Students
Fields student_id,name,surname,address,streetcode,towncode,HeadOfFamily
3. Phonebank
Fields student_id,contacted,towncode
现在我需要一个mysql语句(a)来获取学生表中的总户数,以及(b)联系该特定城镇的学生人数。
直到步骤(a)我管理了哪个并且非常快,这是:
SELECT
t.towncode as towncode,
t.townname as townname,
(SELECT COUNT(*)
FROM students p
WHERE p.towncode=t.towncode
and p.student_hh='H') AS households
FROM
towns t
ORDER BY
t.towncode ASC
但我无法插入另一个SELECT STATEMENT来获取特定城镇的电话号码。
请你帮忙吗?
答案 0 :(得分:0)
对城镇进行每记录计数可能会对您造成伤害。我会首先查询学生表,然后使用加入城镇的表。
对于索引,我会有以下索引
table index
towns ( towncode, townname )
students ( student_hh, towncode )
SELECT
t.towncode as towncode,
t.townname as townname,
TownCnts.households
FROM
towns t
JOIN ( SELECT
p.towncode,
COUNT(*) households
from
students p
where
p.student_hh = 'H'
group by
p.towncode ) as TownCnts
ON t.towncode = TownCnts.towncode
ORDER BY
t.towncode ASC
答案 1 :(得分:0)
假设“call”的数量是具有特定城镇代码的PhoneBank
表中的行数,那么您可以添加另一个子选择:
SELECT t.towncode as towncode, t.townname as townname,
(SELECT COUNT(*)
FROM students p
WHERE p.towncode = t.towncode and p.student_hh='H'
) AS households,
(SELECT COUNT(*)
FROM phonebank pb
WHERE pb.towncode = t.towncode
) AS calls
FROM towns t
ORDER BY t.towncode ASC ;
你的问题有点模糊。您可能希望在第二个查询中使用count(distinct studentid)
,而不是count(*)
。
要优化此查询,请创建以下索引: