📅  最后修改于: 2020-11-29 09:05:37             🧑  作者: Mango
JOIN INDEX是一个物化视图。每当连接索引中引用的基表更新时,其定义就会永久存储并更新数据。 JOIN INDEX可以包含一个或多个表,也可以包含预聚合的数据。连接索引主要用于提高性能。
有不同类型的联接索引可用。
单表联接索引允许根据与基础表中的主索引列不同的主索引列对大型表进行分区。
以下是JOIN INDEX的语法。
CREATE JOIN INDEX
AS
考虑以下雇员和薪水表。
CREATE SET TABLE EMPLOYEE,FALLBACK (
EmployeeNo INTEGER,
FirstName VARCHAR(30) ,
LastName VARCHAR(30) ,
DOB DATE FORMAT 'YYYY-MM-DD',
JoinedDate DATE FORMAT 'YYYY-MM-DD',
DepartmentNo BYTEINT
)
UNIQUE PRIMARY INDEX ( EmployeeNo );
CREATE SET TABLE SALARY,FALLBACK (
EmployeeNo INTEGER,
Gross INTEGER,
Deduction INTEGER,
NetPay INTEGER
)
PRIMARY INDEX ( EmployeeNo )
UNIQUE INDEX (EmployeeNo);
以下是在Employee表上创建名为Employee_JI的Join索引的示例。
CREATE JOIN INDEX Employee_JI
AS
SELECT EmployeeNo,FirstName,LastName,
BirthDate,JoinedDate,DepartmentNo
FROM Employee
PRIMARY INDEX(FirstName);
如果用户使用EmployeeNo上的WHERE子句提交查询,则系统将使用唯一的主索引查询Employee表。如果用户使用employee_name查询employee表,则系统可以使用employee_name访问联接索引Employee_JI。连接索引的行散列在employee_name列上。如果未定义联接索引,并且employee_name未定义为辅助索引,则系统将执行全表扫描以访问行,这非常耗时。
您可以运行以下EXPLAIN计划并验证优化器计划。在以下示例中,您可以看到当表使用Employee_Name列进行查询时,优化器正在使用Join Index而不是基本Employee表。
EXPLAIN SELECT * FROM EMPLOYEE WHERE FirstName='Mike';
*** Help information returned. 8 rows.
*** Total elapsed time was 1 second.
Explanation
------------------------------------------------------------------------
1) First, we do a single-AMP RETRIEVE step from EMPLOYEE_JI by
way of the primary index "EMPLOYEE_JI.FirstName = 'Mike'"
with no residual conditions into Spool 1 (one-amp), which is built
locally on that AMP. The size of Spool 1 is estimated with low
confidence to be 2 rows (232 bytes). The estimated time for this
step is 0.02 seconds.
→ The contents of Spool 1 are sent back to the user as the result of
statement 1. The total estimated time is 0.02 seconds.
通过联接多个表来创建多表联接索引。多表联接索引可用于存储频繁联接表的结果集,以提高性能。
下面的示例通过联接Employee和Salary表创建一个名为Employee_Salary_JI的JOIN INDEX。
CREATE JOIN INDEX Employee_Salary_JI
AS
SELECT a.EmployeeNo,a.FirstName,a.LastName,
a.BirthDate,a.JoinedDate,a.DepartmentNo,b.Gross,b.Deduction,b.NetPay
FROM Employee a
INNER JOIN Salary b
ON(a.EmployeeNo = b.EmployeeNo)
PRIMARY INDEX(FirstName);
每当更新基表Employee或Salary时,联接索引Employee_Salary_JI也会自动更新。如果您正在运行连接Employee和Salary表的查询,那么优化器可以选择直接从Employee_Salary_JI访问数据,而不是联接表。查询上的EXPLAIN计划可用于验证优化器是否选择基表或Join索引。
如果表在某些列上一致地聚合,则可以在表上定义聚合联接索引以提高性能。聚合联接索引的限制之一是它仅支持SUM和COUNT函数。
在以下示例中,将“雇员和薪金”合并在一起以标识每个部门的总薪水。
CREATE JOIN INDEX Employee_Salary_JI
AS
SELECT a.DepartmentNo,SUM(b.NetPay) AS TotalPay
FROM Employee a
INNER JOIN Salary b
ON(a.EmployeeNo = b.EmployeeNo)
GROUP BY a.DepartmentNo
Primary Index(DepartmentNo);