---
# System prepended metadata

title: Join? Left Join? Right Join? Inner Join?傻傻分不清楚
tags: [Hibernate]

---

# Join? Left Join? Right Join? Inner Join?傻傻分不清楚
###### tags: `Hibernate`,`Hibernate`

# 前提
1. 今天我有兩個table分別叫做test1, test2
```sql
create table test1(
	id int not null,
	value char(10)
)
create table test2(
	id int not null,
	value char(10)
)
```
2. 插入數據
```sql 
/*insert data in test1*/
insert into test1 values(1,'testaa');
insert into test1 values(2,'testaa');
insert into test1 values(3,'testaa');
/*insert data in test2*/
insert into test2 values(1,'testaa1');
insert into test2 values(2,'testaa2');
insert into test2 values(4,'testaa3');
```

## Left Join
如果我使用對test1 table left join到test2 table，你可以發現他會以test1為主表，去找test2 table看看id有沒有同時也存在於table1的資料，然後印出來
> sql語法
```sql
select * from test1 p left join test2 b on p.id=b.id
```
- 你會發現印出來的結果，會以test1 table為主，會印出所有test1的結果，可是test2的結果只顯示test1有的
> Result
![](https://i.imgur.com/dPnNk0x.png)

## Right Join
如果使用right join就會以test2的table為主
> sql 語法
```sql
select * from test1 p right join test2 b on p.id=b.id;
```
> result
![](https://i.imgur.com/E8Nw2Zg.png)

## Inner Join
就只會顯示同時存在的資料
> sql 語法
```sql
select * from test1 p inner join test2 b on p.id=b.id;
```
> result
![](https://i.imgur.com/nSDqnhS.png)
