table : Users
userId | named | companyNo | deptNo |
---|---|---|---|
1 | Scott | c01 | d01 |
2 | Tiger | c01 | d02 |
3 | Jacky | c01 | d02 |
4 | Polin | c01 | d03 |
1
2
3
4
5
6
| create table users ( userId char (4), name varchar2(16), companyNo char (3), DeptNo char (3) ); insert into users values ( '0001' , 'Scott' , 'c01' , 'd01' ); insert into users values ( '0002' , 'Tiger' , 'c01' , 'd02' ); insert into users values ( '0003' , 'Jacky' , 'c01' , 'd02' ); insert into users values ( '0004' , 'Polin' , 'c01' , 'd03' ); |
companyNo | name |
---|---|
c01 | ABC Corp. |
c02 | XYZ Corp. |
1
2
3
| create table Company ( companyNo char (3), name varchar2(16) ); insert into Company values ( 'c01' , 'ABC Corp.' ); insert into Company values ( 'c02' , 'XYZ Corp.' ); |
companyNo | DeptNo | name |
---|---|---|
c01 | d01 | Account |
c01 | d02 | Sales |
c01 | d03 | MIS |
c01 | d04 | HR |
1
2
3
4
5
| create table Depts ( companyNo char (3), deptNo char (3), name varchar2(16) ); insert into Depts values ( 'c01' , 'd01' , 'Account' ); insert into Depts values ( 'c01' , 'd02' , 'Sales' ); insert into Depts values ( 'c01' , 'd03' , 'MIS' ); insert into Depts values ( 'c01' , 'd04' , 'HR' ); |
1
2
3
4
5
| SELECT u.*, d. name as deptName, c. name as companyName FROM users u , depts d, company c WHERE 1=1 AND u.deptNo = d.deptNo AND u.companyNo = c.companyNo |
USERID | NAME | COMPANYNO | DEPTNO | DEPTNAME | COMPANYNAME |
---|---|---|---|---|---|
1 | Scott | c01 | d01 | Account | ABC Corp. |
3 | Jacky | c01 | d02 | Sales | ABC Corp. |
2 | Tiger | c01 | d02 | Sales | ABC Corp. |
4 | Polin | c01 | d03 | MIS | ABC Corp. |
1
2
3
4
| SELECT d.*, u. name as userName , c. name as companyName FROM depts d LEFT JOIN users u ON d.deptNo = u.deptNo INNER JOIN company c ON d.companyNO = c.companyNo |
COMPANYNO | DEPTNO | NAME | USERNAME | COMPANYNAME |
---|---|---|---|---|
c01 | d01 | Account | Scott | ABC Corp. |
c01 | d02 | Sales | Jacky | ABC Corp. |
c01 | d02 | Sales | Tiger | ABC Corp. |
c01 | d03 | MIS | Polin | ABC Corp. |
c01 | d04 | HR | (null) | ABC Corp. |
SQL:
1
2
3
4
5
| SELECT d.*, u. name as userName , c. name as companyName FROM depts d, users u, company c WHERE 1=1 AND d.deptno = u.deptno AND d.companyno = c.companyno |
結果:
COMPANYNO | DEPTNO | NAME | USERNAME | COMPANYNAME |
---|---|---|---|---|
c01 | d01 | Account | Scott | ABC Corp. |
c01 | d02 | Sales | Jacky | ABC Corp. |
c01 | d02 | Sales | Tiger | ABC Corp. |
c01 | d03 | MIS | Polin | ABC Corp. |
- INNER JOIN - 兩邊的資料表擁有相同的優先權,要兩邊都有的資料才會被包含在新的資料表。
- RIGHT JOIN - 右邊的資料表擁有優先權,右邊所有的資料都會被包含,而左邊只有符合的資料才會被包含。
- LEFT JOIN - 左邊的資料表擁有優先權,左邊所有的資料都會被包含,而右邊只有符合的資料才會被包含。
沒有留言:
張貼留言