2

请参阅下面的 SQL 查询:

   SELECT SUM(CASE WHEN status=0 AND type  IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_0',
           SUM(CASE WHEN status=0 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_0',
           SUM(CASE WHEN status=2 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_2',
           SUM(CASE WHEN status=2 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_2',
           SUM(CASE WHEN status=3 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_3',
           SUM(CASE WHEN status=3 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_3',
           SUM(CASE WHEN status=4 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_4',
           SUM(CASE WHEN status=4 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_4',
           SUM(CASE WHEN status=5 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_5',
           SUM(CASE WHEN status=5 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_5'
    FROM sales;

需要半秒钟才能得到结果,我想进一步提高性能。有什么建议可以做什么?

salesinnodbstatus type索引。表中超过 50,000 行sales

我的.ini 文件:

[wampmysqld]
port        = 3306
socket      = /tmp/mysql.sock
skip-locking
key_buffer = 16M
max_allowed_packet = 1M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
basedir=c:/wamp/bin/mysql/mysql5.1.36
log-error=c:/wamp/logs/mysql.log
datadir=c:/wamp/bin/mysql/mysql5.1.36/data



#innodb_data_home_dir = C:\mysql\data/
#innodb_data_file_path = ibdata1:10M:autoextend
#innodb_log_group_home_dir = C:\mysql\data/
#innodb_log_arch_dir = C:\mysql\data/
#innodb_additional_mem_pool_size = 2M
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50
innodb_buffer_pool_size = 500M

3GB 内存,英特尔双核 CPU。

4

2 回答 2

4

在查询中添加WHERE子句

SELECT  SUM(CASE WHEN status=0 AND type  IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_0',
        SUM(CASE WHEN status=0 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_0',
        SUM(CASE WHEN status=2 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_2',
        SUM(CASE WHEN status=2 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_2',
        SUM(CASE WHEN status=3 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_3',
        SUM(CASE WHEN status=3 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_3',
        SUM(CASE WHEN status=4 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_4',
        SUM(CASE WHEN status=4 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_4',
        SUM(CASE WHEN status=5 AND type IN (0, 5, 7) THEN 1 ELSE NULL END) AS 'a_5',
        SUM(CASE WHEN status=5 AND type IN (1, 6, 8) THEN 1 ELSE NULL END) AS 'b_5'
FROM    sales
WHERE   status IN (0,2,3,4,5) AND
        type IN (0,1,5,6,7,8)
于 2013-02-23T14:51:35.040 回答
0

您可以使用

SELECT COUNT(*) FROM sales AS 'a0' WHERE status=0 AND type  IN (0, 5, 7) 

其他 7 个查询类似。您可以通过连接将所有查询组合成一个大型查询。

于 2013-02-23T14:59:32.890 回答