1

我用过这个查询

SELECT  COUNT(CASE WHEN C <= 1 THEN 1 END) AS nooffamiliesHavingcount1,
        COUNT(CASE WHEN C BETWEEN 2 AND 4 THEN 1 END) AS nooffamiliesHavingcountbetween2And4,
        COUNT(CASE WHEN C > 4 THEN 1 END) AS nooffamiliesHavingcountgreaterthan3
FROM    (   SELECT  COUNT(*) AS C
            FROM    user where user_id = (select user_id from location where location_id in(select location_id from country where state_name='STATE'))
            GROUP BY House_No
        ) t

这里子查询返回大约 10000 条记录。用户表有 10,00,000 条记录。它花费了太多时间。然后它说的错误是服务器消失了。我正在使用mysql。

我从谷歌搜索。但我没有运气。

我需要对我的表进行哪些更改。如何通过提高查询性能成功执行此查询。请建议我。提前致谢....

4

2 回答 2

2

试试这个查询

SELECT 
  COUNT(CASE WHEN C <= 1 THEN 1 END) AS nooffamiliesHavingcount1,
  COUNT(CASE WHEN C BETWEEN 2 AND 4 THEN 1 END) AS nooffamiliesHavingcountbetween2And4,
  COUNT(CASE WHEN C > 4 THEN 1 END) AS nooffamiliesHavingcountgreaterthan3
FROM  
  (SELECT 
    COUNT(*) AS C
  FROM 
    user u,  
    location l, 
    country c 
  where 
    l.state_name='STATE' AND 
    l.some_other_column_id= 4 AND  <------- Add your condition
    c.location_id = l.location_id AND 
    u.user_id = l.user_id 
  GROUP BY 
    u.House_No) t

使用正确的连接,因为它很容易理解..

SELECT 
  COUNT(CASE WHEN C <= 1 THEN 1 END) AS nooffamiliesHavingcount1,
  COUNT(CASE WHEN C BETWEEN 2 AND 4 THEN 1 END) AS nooffamiliesHavingcountbetween2And4,
  COUNT(CASE WHEN C > 4 THEN 1 END) AS nooffamiliesHavingcountgreaterthan3
FROM  
  (SELECT 
    COUNT(*) AS C
  FROM 
    user u
  INNER JOIN  
    location l
  ON 
    l.state_name='STATE' AND 
    l.some_other_column_id= 4   <------- Add your condition
    u.user_id = l.user_id 
  INNER JOIN
    country c 
  ON 
    c.location_id = l.location_id 
  GROUP BY 
    u.House_No) t

已编辑

在大多数情况下,JOIN 比子查询快,而且子查询更快的情况很少见。我接受使用子查询更合乎逻辑且易于理解,但是在性能方面它不如连接好。如果您使用连接,您的数据库将自行优化您的查询,而子查询则不会。尝试对两个查询都使用解释,您将清楚地了解查询是如何执行的。

希望这可以帮助...

于 2013-04-09T04:34:01.247 回答
1

你可以试试下面:

选择 COUNT(CASE WHEN COUNT( ) <= 1 THEN 1 END)作为 nooffamiliesHavingcount1,COUNT(CASE WHEN COUNT( ) 在 2 和 4 之间然后 1 END)作为 nooffamiliesHavingcountbetween2And4,COUNT(CASE WHEN COUNT(*) > 4 THEN 1 END) AS nooffamiliesHavingcountgreaterthan3 FROM User user Inner JOIN (select user_id from location loc Inner Join country con on loc.location_id =con.location_id where state_name='STATE' )as temp

在 user.user_id =temp.user_id 组 by House_No

于 2013-04-09T04:26:41.543 回答