水煮oracle31----連線查詢&合併查詢

1向2飛發表於2013-09-29
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE連線查詢:兩個或兩個以上表,按照一定的條件,提取出所需的結果;

syntax

SELECT   table1.column, table2.column

FROM table1

[NATURAL JOIN table2] |

[JOIN table2 USING (column_name)] |

[JOIN table2

  ON (table1.column_name = table2.column_name)]|

[LEFT|RIGHT|FULL OUTER JOIN table2

  ON (table1.column_name = table2.column_name)]|

[CROSS JOIN table2];

 

1[NATURAL JOIN table2]---自然連線,(條件:需要做連線的表中,有name相同列並且column

資料型要一致)

注意:如果where中要使用公共列做為條件,不能夠使用表名或表的別名做字首

2[JOIN table2 USING (column_name)]---對自然連線的擴充,如果自然連線中公共列有多個column

如果僅僅想使用其中一列作為連線條件或資料型別不一致,可以使用 using指定要使用的column

3[JOIN table2

  ON (table1.column_name = table2.column_name)]---如果要對結果進行過濾,可以使用on限定條件

4[CROSS JOIN table2]---笛卡爾積

5

LEFT OUTER join

RIGHT OUTER join

FULL OUTER join

 

 

----------------------------

Creating Joins with the USING Clause

---If several columns have the same names but the data types do not match, use the USING clause to specify the columns for the equijoin.

---Use the USING clause to match only one column when more than one column matches.

---The NATURAL JOIN and USING clauses are mutually exclusive.

Using Table Aliases with the USING Clause

---Do not qualify a column that is used in the USING clause.

---If the same column is used elsewhere in the SQL statement, do not alias it.

SELECT l.city, d.department_name

FROM   locations l JOIN departments d

USING (location_id)

WHERE d.location_id = 1400;

 

 

----------------------------

three-way join使用:

ey:

SQL> SELECT employee_id, city, department_name

    FROM   employees e

    JOIN   departments d

    JOIN   locations l

    ON     d.department_id = e.department_id

    ON     d.location_id = l.location_id;

ERROR at line 5:

ORA-00904: "E"."DEPARTMENT_ID": invalid identifier

正確寫法:

SELECT employee_id, city, department_name

FROM   employees e

JOIN   departments d

ON     d.department_id = e.department_id

JOIN   locations l

ON     d.location_id = l.location_id;

 

合併查詢:將多個查詢的結果集進行合併得到一個全新的結果;

集合操作符:

限制:如果選擇列中包含了表示式,則必須使用別名

union |union all |intersect |minus

union:自動去掉結果集中的重複行,並以第一列進行排序

union all:和union相反

intersect:求結果交集,並以第一列進行排序

minus:求結果差集,並以第一列進行排序

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/23890223/viewspace-773606/,如需轉載,請註明出處,否則將追究法律責任。

相關文章