Mysql 通过SQL查询高效获取3列8亿行表的统计信息

Mysql 通过SQL查询高效获取3列8亿行表的统计信息,mysql,sql,sql-server,windows-7,Mysql,Sql,Sql Server,Windows 7,我在SQL server数据库中有一个3列8亿行的数据表 locationID cardID value NY_xxxxx xxxxxx xxxx.xxxx // x : integer digits from 0 to 9 NY_xxxxx xxxxxx xxxx.xxxx NY_xxxxx xxxxxx xxxx.xxxx IA_xxxxx xxxxxx xxxx.xxxx IA_x

我在SQL server数据库中有一个3列8亿行的数据表

  locationID     cardID    value
  NY_xxxxx     xxxxxx    xxxx.xxxx   // x : integer digits from 0 to 9
  NY_xxxxx     xxxxxx    xxxx.xxxx  
  NY_xxxxx     xxxxxx    xxxx.xxxx  
  IA_xxxxx     xxxxxx    xxxx.xxxx  
  IA_xxxxx     xxxxxx    xxxx.xxxx  
  IA_xxxxx     xxxxxx    xxxx.xxxx  
  ...
我需要计算同一位置的不同卡迪德数

另外,我需要计算相同状态下的位置编号。例如,对于上表中的纽约,我们有3个位置

我还需要知道每个州有多少个位置,每个位置有多少个cardID,每个州有多少个cardID


如何通过SQL查询高效地获取这些统计信息?数据表的大小很大。

OP可能已经知道这一点,但下面是如何得到答案,而不考虑效率。首先,如评论中所述,每个位置的卡片:

SELECT locationid, COUNT(DISTINCT cardID)
FROM table 
GROUP BY locationid 
接下来,每个州都会发生同样的事情

SELECT substring(locationid, 1, 2) state, COUNT(DISTINCT cardID)
FROM table 
GROUP BY substring(locationid, 1, 2)
对于一个国家来说

select COUNT(DISTINCT cardID)
from table 
where substring(locationid, 1, 2) = 'NY'
第一个查询的问题是,它将返回类似于NY_1234的locationID。如果你还没有记住NY_1234的外行术语,例如罗切斯特,你必须走出你的数据库去看看它是什么

第二个查询效率低下,因为它必须对大量记录应用子字符串函数。第三种方法效率低下,因为它必须扫描整个表

如果你有一个关系模型,你可以做这样的事情

select municipality, count(distinct cardID)
from table join location on table.locationid = location.locationID
group by municipality

select stateCode, count(distinct cardID)
from table join location on table.locationid = location.locationID
group by stateCode
州代码应该是纽约州、新泽西州等,如果你想要纽约州、新泽西州等,那将是另一个领域

最后,

select count(distinct cardID)
from table join location on table.locationid = location.locationID
where stateCode = 'NY'

后两个关系查询将比单表查询更快,因为它们不必使用函数。使用stateCode上的索引可以加快速度,但即使不这样做,也会扫描更小的表。

您的数据库设计不利于提高效率。具体来说,您的locationID字段不好。@Dan Bracuk,请您解释清楚好吗?为什么没有效率?如何获取所需信息?谢谢对于那些投票否决我的帖子的人,请给出一个理由。这有助于我提高我的帖子质量。谢谢
SELECT COUNT(DISTINCT cardd),locationid FROM table GROUP BY locationid
location上的索引会有所帮助。如果需要特定位置,请添加WHERE子句。MySQL不是SQL Server如何提高前两个查询的效率?