有一张表包含150万条记录,需要在网页上显示不同条件的数量。
假设表格结构如下:
+-------+------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| userId| int(11) | YES | | NULL | |
| cona | tinyint(4) | YES | | NULL | |
| conb | tinyint(4) | YES | | NULL | |
| conc | tinyint(4) | YES | | NULL | |
| date | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+------------+------+-----+-------------------+-----------------------------+
需要查询具有不同条件的用户数量,如下所示:
SELECT count(DISTINCT userId) FROM test
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE cona=0
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE cona=1
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=0
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=1 AND conc=0
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=1 AND conc>0 AND date IS NOT NULL AND NOW() > date
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=1 AND conc=1 AND date IS NOT NULL AND NOW() <= date
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=1 AND conc=2 AND date IS NOT NULL AND NOW() <= date
UNION ALL
SELECT count(DISTINCT userId) FROM test WHERE conb=2
每个计数查询的成本大约在300~500ms之间,但是联合所有计数查询使得这个sql成本大约为8~9s。
我尝试在userId, cona, conb, conc
ALTER TABLE `test` ADD INDEX( `userId`);
ALTER TABLE `test` ADD INDEX( `cona`);
ALTER TABLE `test` ADD INDEX( `conb`);
ALTER TABLE `test` ADD INDEX( `conc`);
但成本与以前相同。
我真的没有sql优化的经验
是否可以优化union sql?