Querying Joined Tables

Join Types

Multiple joins are necessary for accomplishing complex queries. Joins are classified into inner joins and outer joins. Each type of joins have their subtypes.

To better illustrate the differences between these joins, the following provides some examples.

Create the sample tables student and math_score and insert data into them. Set enable_fast_query_shipping to off (on by default), that is, the query optimizer uses the distributed framework. Set explain_perf_mode to pretty (default value) to specify the EXPLAIN display format.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
CREATE TABLE student(
  id INTEGER,
  name varchar(50)
);

CREATE TABLE math_score(
  id INTEGER,
  score INTEGER
);

INSERT INTO student VALUES(1, 'Tom');
INSERT INTO student VALUES(2, 'Lily');
INSERT INTO student VALUES(3, 'Tina');
INSERT INTO student VALUES(4, 'Perry');

INSERT INTO math_score VALUES(1, 80);
INSERT INTO math_score VALUES(2, 75);
INSERT INTO math_score VALUES(4, 95);
INSERT INTO math_score VALUES(6, NULL);

SET enable_fast_query_shipping = off;
SET explain_perf_mode = pretty;

Inner Join

Outer Join

Differences Between the ON Condition and the WHERE Condition in Multi-Table Query

According to the preceding join syntax, except natural join and cross join, the ON condition (USING is converted to the ON condition during query parsing) is used on the join result of both the two tables. Generally, the WHERE condition is used in the query statement to restrict the query result. The ON join condition and WHERE filter condition do not contain conditions that can be pushed down to tables. The differences between ON and WHERE are as follows:

To sum up, the ON condition is used when two tables are joined. After the join result set of two tables is generated, the WHERE condition is used.