例1. 两个表右连接,除了连接列之外没有其他相同列名:
t1= table(1 2 3 3 as id, 7.8 4.6 5.1 0.1 as value)
t2 = table(5 3 1 as id, 300 500 800 as qty);
t1;
id |
value |
1 |
7.8 |
2 |
4.6 |
3 |
5.1 |
3 |
0.1 |
t2;
SELECT id, value, qty FROM t1 RIGHT OUTER JOIN t2 ON t1.id=t2.id
//等价于 SELECT id, value, qty FROM t1 RIGHT JOIN t2 ON t1.id=t2.id
id |
value |
qty |
5 |
|
300 |
3 |
5.1 |
500 |
3 |
0.1 |
500 |
1 |
7.8 |
800 |
我们无需指定value和qty来自哪个表。系统首先会在右表中定位这两个列,如果右表没有这两个列,系统会在左表定位。
SELECT id, value, qty FROM t2 RIGHT JOIN t1 ON t2.id=t1.id
id |
value |
qty |
1 |
7.8 |
800 |
2 |
4.6 |
|
3 |
5.1 |
500 |
3 |
0.1 |
800 |
例2. 两个表右连接,它们具有相同列名,但是不作为连接列:
t1 = table(1 2 3 3 as id, 7.8 4.6 5.1 0.1 as value, 4 3 2 1 as x)
t2 = table(5 3 1 as id, 300 500 800 as qty, 44 66 88 as x);
t1;
id |
value |
x |
1 |
7.8 |
4 |
2 |
4.6 |
3 |
3 |
5.1 |
2 |
3 |
0.1 |
1 |
t2;
id |
qty |
x |
5 |
300 |
44 |
3 |
500 |
66 |
1 |
800 |
88 |
SELECT id, value, qty, x FROM t1 RIGHT JOIN t2 ON t1.id=t2.id
id |
value |
qty |
x |
5 |
|
300 |
44 |
3 |
5.1 |
500 |
66 |
3 |
0.1 |
500 |
66 |
1 |
7.8 |
800 |
88 |
SELECT id, value, qty, t1.x FROM t1 RIGHT JOIN t2 ON t1.id=t2.id
id |
value |
qty |
x |
5 |
|
300 |
|
3 |
5.1 |
500 |
2 |
3 |
0.1 |
500 |
1 |
1 |
7.8 |
800 |
4 |
如果左表(t1)和右表(t2)有除连接列以外其他相同的字段名(x),我们从左表(t1)中选择字段名为x的数据时,需要指定x所在的表:t1.x。
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id=t2.id
id |
qty |
x |
value |
t1_x |
5 |
300 |
44 |
|
|
3 |
500 |
66 |
5.1 |
2 |
3 |
500 |
66 |
0.1 |
1 |
1 |
800 |
88 |
7.8 |
4 |
在上面的例子中,从t1和t2选择字段名为x的数据,并且把结果中t1的x字段重命名为t1_x。
例3. 多个连接列:
t1=table(1 1 2 2 3 3 as x, 1 2 2 3 3 4 as y, 1..6 as a);
t2=table(0 1 1 2 2 3 as x, 1 2 3 3 4 5 as y, 11..16 as b);
t1;
x |
y |
z |
1 |
1 |
1 |
1 |
2 |
2 |
2 |
2 |
3 |
2 |
3 |
4 |
3 |
3 |
5 |
3 |
4 |
6 |
t2;
x |
y |
b |
0 |
1 |
11 |
1 |
2 |
12 |
1 |
3 |
13 |
2 |
3 |
14 |
2 |
4 |
15 |
3 |
5 |
16 |
SELECT * FROM t1 RIGHT JOIN t2 ON t1.x=t2.x AND t1.y=t2.y
// x, y是连接列
x |
y |
b |
a |
0 |
1 |
11 |
|
1 |
2 |
12 |
2 |
1 |
3 |
13 |
|
2 |
3 |
14 |
4 |
2 |
4 |
15 |
|
3 |
5 |
16 |
|
t2.rename!(`x`y, `x2`y2);
t2
x2 |
y2 |
b |
0 |
1 |
11 |
1 |
2 |
12 |
1 |
3 |
13 |
2 |
3 |
14 |
2 |
4 |
15 |
3 |
5 |
16 |
SELECT * FROM t1 RIGHT JOIN t2 ON t1.x=t2.x2 AND t1.y=t2.y2
// t1.x, t1.y t2.x2, t2.y2是连接列
x |
y |
b |
a |
0 |
1 |
11 |
|
1 |
2 |
12 |
2 |
1 |
3 |
13 |
|
2 |
3 |
14 |
4 |
2 |
4 |
15 |
|
3 |
5 |
16 |
|
例4. 指定过滤条件
t1= table(1 2 3 3 as id1, 7.8 4.6 5.1 0.1 as value)
t2 = table(5 3 1 as id2, 300 500 800 as qty);
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id1=t2.id2 AND t1.value>1 AND t1.value<6 AND t2.qty>300
id1 |
qty |
value |
5 |
300 |
|
3 |
500 |
5.1 |
1 |
800 |
|