对于不同字段的 or 查询怎样建立所以查询速度快?
这样的
我需要得到总数
建立 A+B 的索引对于这种 OR 的查询好像不管用
单表千万条数据的
这样的
我需要得到总数
建立 A+B 的索引对于这种 OR 的查询好像不管用
单表千万条数据的
UNION ALL 只能用于数据, 而不能用于 count(*)吧?
先查 count(*) where a=1, 得 x
再查 count(*) where b=2, 得 y
再查 count(*) where a=1 and b=2, 得 z
然后用 x+y-z 就得到 where a=1 or b=2 的个数
需要 3 个索引: 单独 a 的, 单独 b 的, a 和 b 的
只需要在 a,b 列上单独建索引就行,这是执行计划:
QUERY PLAN
Aggregate (cost=22119.36..22119.37 rows=1 width=8) (actual time=21.540..21.542 rows=1 loops=1)
-> Bitmap Heap Scan on a (cost=300.17..22081.89 rows=14988 width=0) (actual time=1.539..20.603 rows=15506 loops=1)
Recheck Cond: ((city_name = ‘北京’::text) OR (city_code = ‘120000’::text))
Heap Blocks: exact=3805
-> BitmapOr (cost=300.17..300.17 rows=15445 width=0) (actual time=1.153..1.154 rows=0 loops=1)
-> Bitmap Index Scan on index_a (cost=0.00..214.28 rows=11449 width=0) (actual time=0.806..0.806 rows=11534 loops=1)
Index Cond: (city_name = ‘北京’::text)
-> Bitmap Index Scan on index_b (cost=0.00..78.39 rows=3996 width=0) (actual time=0.346..0.346 rows=3972 loops=1)
Index Cond: (city_code = ‘120000’::text)
Planning Time: 0.128 ms
Execution Time: 21.566 ms
+—-+————-+——————–+————+————-+———————+—————-+———+——+——–+———-+———————————————–+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+—-+————-+——————–+————+————-+———————+—————-+———+——+——–+———-+———————————————–+
| 1 | SIMPLE | table | NULL | index_merge | index_a,index_b,index_ab | index_ab,index_b | 5,5 | NULL | 639711 | 100.00 | Using sort_union(index_ab,index_b); Using where |
+—-+————-+——————–+————+————-+———————+—————-+———+——+——–+———-+———————————————–+
—————-分隔符————————
命令: SELECT count(*) FROM table WHERE `a`=21 OR `b`=4301;
+———-+
| count(*) |
+———-+
| 690113 |
+———-+
1 row in set (2 min 23.63 sec)
—————-分隔符————————
————————-
您是说 explain 的 rows 639711 就是总条数吗?
但是和 count 的 690113 数量不同
@taogen