原创转载请注明出处:http://agilestyle.iteye.com/blog/1227808
创建表STUDENT
CREATE TABLE STUDENT
(
SID INTEGER,
NAME VARCHAR(20) NOT NULL,
CONSTRAINTS STUDENT_SID_PK PRIMARY KEY(SID)
);
创建表EXAM
CREATE TABLE EXAM
(
EID INTEGER,
SCORE NUMBER(2) NOT NULL,
CONSTRAINTS STUDENT_EXAM_EID_FK FOREIGN KEY(EID) REFERENCES STUDENT(SID)
);
查看STUDENT表结构
查看EXAM表结构
插入数据
INSERT INTO STUDENT(SID, NAME) VALUES(1, 'Struts');
INSERT INTO STUDENT(SID, NAME) VALUES(2, 'Spring');
INSERT INTO STUDENT(SID, NAME) VALUES(3, 'Hibernate');
INSERT INTO EXAM(EID, SCORE) VALUES(1, 99);
INSERT INTO EXAM(EID, SCORE) VALUES(2, 88);
SQL INNER JOIN 关键字
INNER JOIN 关键字在表中存在至少一个匹配时返回行。
SQL INNER JOIN 语法
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
或者:
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
Note:INNER JOIN 与 JOIN 是相同的
内连接 (显示两表id匹配的)
SELECT S.SID, S.NAME, E.EID, E.SCORE
FROM STUDENT S
INNER JOIN EXAM E
ON S.SID = E.EID;
结果
SQL LEFT JOIN 关键字
LEFT JOIN 关键字从左表(table1)返回所有的行,即使右表(table2)中没有匹配。如果右表中没有匹配,则结果为 NULL
SQL LEFT JOIN 语法
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
或者:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Note: 在某些数据库中,LEFT JOIN 称为 LEFT OUTER JOIN。
左连接(显示join 左边的表的所有数据)
SELECT S.SID, S.NAME, E.EID, E.SCORE
FROM STUDENT S
LEFT OUTER JOIN EXAM E
ON S.SID = E.EID;
结果
SQL RIGHT JOIN 关键字
RIGHT JOIN 关键字从右表(table2)返回所有的行,即使左表(table1)中没有匹配。如果左表中没有匹配,则结果为 NULL。
SQL RIGHT JOIN 语法
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
或者:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Note:在某些数据库中,RIGHT JOIN 称为 RIGHT OUTER JOIN
右连接(显示join 右边的表的所有数据)
SELECT S.SID, S.NAME, E.EID, E.SCORE
FROM STUDENT S
RIGHT OUTER JOIN EXAM E
ON S.SID = E.EID;
结果
SQL FULL OUTER JOIN 关键字
FULL OUTER JOIN 关键字只要左表(table1)和右表(table2)其中一个表中存在匹配,则返回行.
FULL OUTER JOIN 关键字结合了 LEFT JOIN 和 RIGHT JOIN 的结果。
SQL FULL OUTER JOIN 语法
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
全连接
SELECT S.SID, S.NAME, E.EID, E.SCORE
FROM STUDENT S
FULL OUTER JOIN EXAM E
ON S.SID = E.EID;
结果