mysql null join

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
mysql> create table t1 (row_id int unsigned not null auto_increment primary key, value int default null);
Query OK, 0 rows affected (0.02 sec)
mysql> create table t2 like t1;
Query OK, 0 rows affected (0.02 sec)
mysql> insert into t1 (value) values (1), (2), (NULL);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> insert into t2 (value) values (1), (2), (NULL);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from t1, t2;
+--------+-------+--------+-------+
| row_id | value | row_id | value |
+--------+-------+--------+-------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 1 | 1 |
| 3 | NULL | 1 | 1 |
| 1 | 1 | 2 | 2 |
| 2 | 2 | 2 | 2 |
| 3 | NULL | 2 | 2 |
| 1 | 1 | 3 | NULL |
| 2 | 2 | 3 | NULL |
| 3 | NULL | 3 | NULL |
+--------+-------+--------+-------+
9 rows in set (0.00 sec)
mysql> select * from t1, t2 where t1.value = t2.value;
+--------+-------+--------+-------+
| row_id | value | row_id | value |
+--------+-------+--------+-------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
+--------+-------+--------+-------+
2 rows in set (0.01 sec)
mysql> select * from t1, t2 where t1.value = t2.value or t1.value is null or t2.value is null;
+--------+-------+--------+-------+
| row_id | value | row_id | value |
+--------+-------+--------+-------+
| 1 | 1 | 1 | 1 |
| 3 | NULL | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | NULL | 2 | 2 |
| 1 | 1 | 3 | NULL |
| 2 | 2 | 3 | NULL |
| 3 | NULL | 3 | NULL |
+--------+-------+--------+-------+
7 rows in set (0.00 sec)
mysql> select * from t1;
+--------+-------+
| row_id | value |
+--------+-------+
| 1 | 1 |
| 2 | 2 |
| 3 | NULL |
| 4 | NULL |
+--------+-------+
4 rows in set (0.00 sec)
mysql> select * from t2;
+--------+-------+
| row_id | value |
+--------+-------+
| 1 | 1 |
| 2 | 2 |
| 3 | NULL |
+--------+-------+
3 rows in set (0.00 sec)
mysql> select * from t1 left join t2 using (value);
+-------+--------+--------+
| value | row_id | row_id |
+-------+--------+--------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| NULL | 3 | NULL |
| NULL | 4 | NULL |
+-------+--------+--------+
4 rows in set (0.00 sec)
mysql> select * from t1 right join t2 using (value);
+-------+--------+--------+
| value | row_id | row_id |
+-------+--------+--------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| NULL | 3 | NULL |
+-------+--------+--------+
3 rows in set (0.00 sec)