索引问题
使用索引场景:
1:匹配全值(match the full value)对索引中所有列都指定具体值,即是对索引中的所有列都有等值匹配的条件。
2:匹配值的范围查询(match a range of values)对索引的值能够进行范围查询
3:匹配最左前缀(match a leftmost prefix)仅仅使用索引中最左边列进行查询,(复合索引)
4:仅仅对索引进行查询(index only query)当查询的列都在索引的字段中时,查询的效率更高
5:匹配列前缀:(match a column prefix)仅仅使用索引中的第一列,并且只包含索引第一列的开头一部分进行查找。
6:能够实现索引匹配部分精确而其他部分进行范围匹配
7:如果类名是索引,那么使用column_name is null 就会使用索引。
存在索引但不使用的场景
1:以%开头的like查询不能利用 B-tree索引
2:数据类型出现隐式转换的时候不会使用索引,特别是当列类型是字符串,要在where条件中把字符常量值用引号引起来
3:复合索引情况下,假如查询条件不包含索引列最左边部分,即不满足最左原则是不会使用最左索引的
4:如果mysql估计使用索引比全表扫描更慢,则不会使用索引
5:用or分开的条件,如果or前的条件中列有索引,而后面的列中没有索引,那么涉及的索引都不会被用到
用bit_or () / bit_and()函数和group by做统计。
mysql> desc s;
+-------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| customer_id | int(11) | YES | | NULL | |
| kind | int(11) | YES | | NULL | |
+-------------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> insert into s values(1,1,5),(2,1,4);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> insert into s values(3,2,3),(4,2,4);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from s;
+------+-------------+------+
| id | customer_id | kind |
+------+-------------+------+
| 1 | 1 | 5 |
| 2 | 1 | 4 |
| 3 | 2 | 3 |
| 4 | 2 | 4 |
+------+-------------+------+
4 rows in set (0.00 sec)
用bit_or() 相当于把kind的各个值做一个“或”操作。 统计这两个顾客都买过什么商品
mysql> select customer_id ,bit_or(kind) from s group by customer_id;
+-------------+--------------+
| customer_id | bit_or(kind) |
+-------------+--------------+
| 1 | 5 |
| 2 | 7 |
+-------------+--------------+
2 rows in set (0.01 sec)
用bit_and() 相当于把kind的各个值做一个“与”操作。 统计每个顾客每次来本超市都会买的商品
mysql> select customer_id ,bit_and(kind) from s group by customer_id;
+-------------+---------------+
| customer_id | bit_and(kind) |
+-------------+---------------+
| 1 | 4 |
| 2 | 0 |
+-------------+---------------+
2 rows in set (0.00 sec)