简体   繁体   English

MySQL Group运行太慢

[英]MySQL Group running too slow

I have a 3 MySQL tables which I need to get results from and which are: 我有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

Now I need a mysql statement (a) to get the total number of households from the students table and also (b) the number of students contacted for that particular town. 现在,我需要一个mysql语句(a)从“学生”表中获取家庭总数,以及(b)为该特定城镇联系的学生数。

up to step (a) I managed which and is extremely fast which is: 到步骤(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 

but I cannot manage to insert as well another SELECT STATEMENT to get the number of calls fr that particular town. 但我无法设法插入另一个“ SELECT STATEMENT”来获取该特定城镇的电话数量。

Can you kindly assist please? 你能帮忙吗?

Doing a per-record count on towns is probably hurting you. 对城镇进行单项记录可能会伤害您。 I would pre-query the students table first, THEN use that joined to the towns. 我会先查询学生表,然后再使用连接到城镇的表。

For indexes, I would have the following indexes 对于索引,我将具有以下索引

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 

Assuming that the number of "calls" is the number of rows in the PhoneBank table with a particular town code, then you can add another subselect: 假设“呼叫”数是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 ;

Your question is a little vague. 您的问题有点含糊。 It is possible that you want count(distinct studentid) in the second query, rather than count(*) . 您可能希望在第二个查询中使用count(distinct studentid) ,而不是count(*)

To optimize this query, create the following indexes: 要优化此查询,请创建以下索引:

  • towns(towncode) 城镇(区号)
  • students(towncode, student_hh) 学生(区号,student_hh)
  • phonebank(towncode) 电话银行(区号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM