○ SELECT * FROM SomeTable WHERE col_1 = 10 AND col_2 = 100 AND col_3 = 500;
○ SELECT * FROM SomeTable WHERE col_1 = 10 AND col_2 = 100 ;
× SELECT * FROM SomeTable WHERE col_1 = 10 AND col_3 = 500 ;
× SELECT * FROM SomeTable WHERE col_2 = 100 AND col_3 = 500 ;
× SELECT * FROM SomeTable WHERE col_2 = 100 AND col_1 = 10 ;
5.9.3. 联合索引中的第一列(col_1)必须写在查询条件的开头,而且索引中列的顺序不能颠倒
5.9.4. 有些数据库里顺序颠倒后也能使用索引,但是性能还是比顺序正确时差一些
5.9.5. 如果无法保证查询条件里列的顺序与索引一致,可以考虑将联合索引拆分为多个索引
5.10. 使用LIKE谓词进行后方一致或中间一致的匹配
5.10.1. 只有前方一致的匹配才能用到索引
5.10.2.
× SELECT * FROM SomeTable WHERE col_1 LIKE '%a';
× SELECT * FROM SomeTable WHERE col_1 LIKE '%a%';
○ SELECT * FROM SomeTable WHERE col_1 LIKE 'a%';
5.11. 进行默认的类型转换
5.11.1. 默认的类型转换不仅会增加额外的性能开销,还会导致索引不可用
5.11.2. 在需要类型转换时显式地进行类型转换
6. 减少中间表
6.1. 子查询的结果会被看成一张新表,这张新表与原始表一样,可以通过代码进行操作
6.2. 灵活使用HAVING子句
6.2.1. 对聚合结果指定筛选条件时不需要专门生成中间表
6.2.2.
SELECT sale_date, MAX(quantity)
FROM SalesHistory
GROUP BY sale_date
HAVING MAX(quantity) >= 10;
SELECT id, state, city
FROM Addresses1 A1
WHERE state IN (SELECT state
FROM Addresses2 A2
WHERE A1.id = A2.id)
AND city IN (SELECT city
FROM Addresses2 A2
WHERE A1.id = A2.id);
6.3.2.
SELECT *
FROM Addresses1 A1
WHERE id || state || city
IN (SELECT id || state|| city
FROM Addresses2 A2);
6.3.2.1. 子查询不用考虑关联性,而且只执行一次就可以
6.3.3.
SELECT *
FROM Addresses1 A1
WHERE (id, state, city)
IN (SELECT id, state, city
FROM Addresses2 A2);