MYSQL Count(Distinct)Group By

时间:2015-04-23 12:17:39

标签: mysql

此选择可以保持超时:

SELECT COUNT(DISTINCT `invoices`) 
FROM `data` 
WHERE date BETWEEN '2013-07-01' AND '2014-06-30' 
GROUP BY `store`

我在发票,日期,商店和发票,商店,日期上制作了索引。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

我也有同样的问题。我想你正在用一张大桌子。我通过更改配置文件中的一些值来解决它:

key_buffer = 128M
thread_stack = 128K
thread_cache_size = 8
table_cache = 8192
max_heap_table_size = 256M
query_cache_limit = 4M
query_cache_size = 512M

innodb_file_per_table
innodb_buffer_pool_size = 4G 

innodb_log_file_size = 512M
skip_name_resolve

join_buffer_size = 128M
sort_buffer_size = 2M
read_rnd_buffer_size = 2M 

key_buffer_size         = 64M
sort_buffer_size        = 1M
tmp_table_size          = 256M
max_heap_table_size     = 512M
read_buffer_size        = 64K
read_rnd_buffer_size    = 64K
myisam_sort_buffer_size = 256M

但是这些价值观根据你的电脑和工作而变化。我建议你搜索一下“大数据的mysql配置”。您将找到有关其含义的一些信息。顺便说一下,你的表中也应该有一个主键。我认为它也会影响性能。最后你应该检查mysql中的首选项。您可能需要在sql编辑器部分下增加mysql会话设置。我希望它有所帮助。

答案 1 :(得分:0)

试试这个

SELECT store, COUNT(DISTINCT invoices) 
FROM data 
WHERE date BETWEEN '2013-07-01' AND '2014-06-30' 
GROUP BY store

答案 2 :(得分:0)

SELECT `store`, COUNT(*) FROM 
   (SELECT `store`, `invoices`
          FROM `data` 
         WHERE date BETWEEN '2013-07-01' AND '2014-06-30' 
       GROUP BY `store`, `invoices`
   ) tbl
GROUP BY `store`

这是一个小提琴,没​​有date列并检查......

http://sqlfiddle.com/#!9/fb83c/5/0