sql T-SQL所有类型的Joins.sql
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql T-SQL所有类型的Joins.sql相关的知识,希望对你有一定的参考价值。
--Add unique constraint to combination of two columns
--no repeat combination of two columns in sql server
ALTER TABLE dbo.tbl_student
ADD CONSTRAINT uq_name_and_reg_combination UNIQUE(name, reg)
ALTER TABLE dbo.tbl_student
DROP CONSTRAINT uq_name_and_reg_combination;
ALTER TABLE dbo.tbl_student
ADD CONSTRAINT uq_reg UNIQUE(reg)
--==========Only JOIN (by default it is INNER JOIN) =============
-- INNER JOIN is the default if you don't specify the type when you use the word JOIN.
SELECT s.*,d.department_name
FROM tbl_student s
JOIN tbl_department d
ON s.department_id=d.department_id
--==========INNER JOIN========
SELECT s.*,d.department_name
FROM tbl_student s
INNER JOIN tbl_department d
ON s.department_id=d.department_id
--=========OUTER JOINS===========
SELECT s.*,d.department_name
FROM tbl_student s
LEFT OUTER JOIN tbl_department d
ON s.department_id=d.department_id
SELECT s.*,d.department_name
FROM tbl_student s
RIGHT OUTER JOIN tbl_department d
ON s.department_id=d.department_id
SELECT s.*,d.department_name
FROM tbl_student s
FULL OUTER JOIN tbl_department d
ON s.department_id=d.department_id
-- MORE 3 TYPES OF OUTER JOIN http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
--1. LEFT JOIN EXCLUDING INNER JOIN
--2. RIGHT JOIN EXCLUDING INNER JOIN
--3. OUTER JOIN EXCLUDING INNER JOIN
--1. LEFT JOIN EXCLUDING INNER JOIN
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
--2. RIGHT JOIN EXCLUDING INNER JOIN
SELECT <select_list>
FROM Table_A A
RIGHT JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL
--3. OUTER JOIN EXCLUDING INNER JOIN
SELECT <select_list>
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.Key = B.Key
WHERE A.Key IS NULL OR B.Key IS NULL
--=========CROSS JOIN / CARTESIAN JOIN===========
SELECT s.*,d.department_name
FROM tbl_student s
CROSS JOIN tbl_department d
--==========SELF JOINS=========
SELECT E.employee_name as Employee, M.employee_name as Manager
FROM tbl_employee E
INNER JOIN tbl_employee M
ON E.manager_id = M.employee_id
SELECT E.employee_name as Employee, M.employee_name as Manager
FROM tbl_employee E
LEFT OUTER JOIN tbl_employee M
ON E.manager_id = M.employee_id
SELECT E.employee_name as Employee, M.employee_name as Manager
FROM tbl_employee E
RIGHT OUTER JOIN tbl_employee M
ON E.manager_id = M.employee_id
SELECT E.employee_name as Employee, M.employee_name as Manager
FROM tbl_employee E
FULL OUTER JOIN tbl_employee M
ON E.manager_id = M.employee_id
SELECT E.employee_name as Employee, M.employee_name as Manager
FROM tbl_employee E
CROSS JOIN tbl_employee M
以上是关于sql T-SQL所有类型的Joins.sql的主要内容,如果未能解决你的问题,请参考以下文章