请参阅下面的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;
获得结果需要半秒钟,我希望进一步提高性能。任何建议可以做什么?
sales
表格为innodb
,status
type
已编入索引。 sales
表中超过50,000行。
my.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 Ram,Intel双核CPU。
答案 0 :(得分: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)
答案 1 :(得分:0)
您可以使用
提取值SELECT COUNT(*) FROM sales AS 'a0' WHERE status=0 AND type IN (0, 5, 7)
和其他7个查询类似。您可以将所有查询组合成一个带有连接的大型查询。