1.查询处理步骤 查询分析-查询检查-查询优化-查询执行 具体的看流程图: 2.实现查询操作及算法
简单的全表扫描算法(table scan) 比如,一般查询都用这个算法: select * from student where age <20 ; 算法思想: 假设可以使用的内存为M块,步骤如下: (1)按照物理次序读student的M块到内存; (2)检查内存的每个元组,如果t满足选择条件,则输出t; (3)如果student还有其他块没处理,则继续执行(1)和(2)。 应用:一般应用于规模比较小的表,这用算法简单有效;如果用到规模大的表,它的选择率较低时,这个算法效率很低(满足条件元组数占全表的比例)。 2.索引扫描算法(index scan) 如果选择条件中的属性上有索引(hash索引或者B+树索引)可以用索引扫描的方法,通过索引先找到满足条件的元组指针,再通过元组指针在查询的基本表中找到元组。 应用:解决1中效率较低的问题,我们可以利用索引的选择算法;但要注意一点,除了对表的扫描操作,还有加上B+树索引的扫描操作。索引算法代码(java):
import java.util.Arrays; public class IndexSearch { // 主表 static int[] students = { 101, 102, 103, 104, 105, 0, 0, 0, 0, 0, 201, 202, 203, 204, 0, 0, 0, 0, 0, 0, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0 }; // 索引表 static IndexItem[] indexItem = { new IndexItem(1, 0, 5), new IndexItem(2, 10, 4), new IndexItem(3, 20, 3), }; // 查找数据 public static int indexSearch(int key) { IndexItem item = null; // 建立索引规则 int index = key / 100; // 首先去索引找 for (int i = 0; i < indexItem.length; i++) { if (indexItem[i].index == index) { item = new IndexItem(index, indexItem[i].start, indexItem[i].length); break; } } // 如果item为null,则说明在索引中查找失败 if (item == null) return -1; for (int i = item.start; i < item.start + item.length; i++) { if (students[i] == key) { return i; } } return -1; } // / 插入数据 public static int insert(int key) { IndexItem item = null; // 建立索引规则 int index = key / 100; int i = 0; for (i = 0; i < indexItem.length; i++) { // 获取到了索引 if (indexItem[i].index == index) { item = new IndexItem(index, indexItem[i].start, indexItem[i].length); break; } } if (item == null) return -1; // 更新主表 students[item.start + item.length] = key; // 更新索引表 indexItem[i].length++; return 1; } public static void main(String[] args) { int value = 205; // 将205插入集合中,过索引 int index = insert(value); insert(308); // 如果插入成功,获取205元素所在的位置 if (index == 1) { System.out.println("\n插入后数据:" + Arrays.toString(students)); System.out.println("\n数据元素:205在数组中的位置为 " + indexSearch(205) + "位"); } } } // 索引项实体 class IndexItem { // 对应主表的值 public int index; // 主表记录区间段的开始位置 public int start; // 主表记录区间段的长度 public int length; public IndexItem() { } public IndexItem(int index, int start, int length) { this.index = index; this.start = start; this.length = length; } }