來源:https://blog.csdn.net/qq_16590169/article/details/103332505
1 數據准備
emp1表: 1 張三 A1 2 李四 A2 3 王五 A3 4 小明 B1 dept1表: A1 財務 A2 人事 create table if not exists emp1 ( emp_no string ,name string ,dept_no string )row format delimited fields terminated by '\t'; create table if not exists dept1 ( dept_no string ,dept_name string )row format delimited fields terminated by '\t';
2 LEFT JOIN(RIGHT JOIN)驗證
2.1 LEFT JOIN(RIGHT JOIN)只帶ON的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 left join dept1 t2 on t1.dept_no = t2.dept_no; 張三 A1 A1 李四 A2 A2 王五 A3 NULL 小明 B1 NULL
2.2 LEFT JOIN(RIGHT JOIN)只ON和AND的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 left join dept1 t2 on t1.dept_no = t2.dept_no and t2.dept_no='A2'; 張三 A1 NULL 李四 A2 A2 王五 A3 NULL 小明 B1 NULL
2.3 LEFT JOIN(RIGHT JOIN)只ON和WHERE的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 left join dept1 t2 on t1.dept_no = t2.dept_no where t2.dept_no='A2'; 李四 A2 A2
2.4 LEFT JOIN(RIGHT JOIN) ON 1=1
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 left join dept1 t2 on 1=1; 張三 A1 A1 張三 A1 A2 張三 A1 李四 A2 A1 李四 A2 A2 李四 A2 王五 A3 A1 王五 A3 A2 王五 A3 小明 B1 A1 小明 B1 A2 小明 B1
2.5 LEFT JOIN(RIGHT JOIN) ON 1=2
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 left join dept1 t2 on 1=2; 張三 A1 NULL 李四 A2 NULL 王五 A3 NULL 小明 B1 NULL
2.6 left join(right join)小結
- 做left join(right join)的時候,只用on連接,就是左邊全部展示,右邊有關聯數據就顯示,沒有就顯示null;用on和and連接,也是左邊全部顯示,右邊符合and條件的顯示,否則顯示為null;用on和where連接,達到了過濾的效果,只顯示符合where條件的數據。
- 做left join(right join)的時候,使用on后恆為真,就會將兩表進行笛卡爾積(等價於直接join,沒有on關聯);使用on后恆不為真,只顯示左表的全部,右邊關聯的顯示全為null。
3 INNER JOIN驗證
3.1 INNER JOIN只帶ON的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 inner join dept1 t2 on t1.dept_no = t2.dept_no; 張三 A1 A1 李四 A2 A2
3.2 INNER JOIN只ON和AND的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 inner join dept1 t2 on t1.dept_no = t2.dept_no and t2.dept_no='A2'; 李四 A2 A2
3.2 INNER JOIN只ON和WHERE的HQL
select t1.name,t1.dept_no,t2.dept_no from emp1 t1 inner join dept1 t2 on t1.dept_no = t2.dept_no where t2.dept_no='A2'; 李四 A2 A2
3.3 inner join小結
做inner join的時候,使用on關聯,會把關聯表符合on條件的內容顯示,不符合的全部過濾;使用on和and或者on和where效果是一樣的。