id name
1, Jack
2, Tom
3, Kity
4, nono
--表exam
id grade
1, 56
2, 76
11, 89
内连接 (显示两表id匹配的)
select stu.id,exam.id,stu.name, exam.grade from stu inner join exam on stu.id=exam.id
stu.id exam.id name grade
--------------------------------
1 1 Jack 56
2 2 Tom 76
左连接(显示join 左边的表的所有数据,exam只有两条记录,所以stu.id,grade 都用NULL 显示)
select stu.id,exam.id,stu.name, exam.grade from stu left join exam on stu.id=exam.id
1 1 Jack 56
2 2 Tom 76
3 NULL Kity NULL
4 NULL nono NULL
右连接(与作连接相反,显示join右边表的所有数据)
select stu.id,exam.id,stu.name, exam.grade from stu right join exam on stu.id=exam.id
1 1 Jack 56
2 2 Tom 76
NULL 11 NULL 89
1.
a. 并集UNION
SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2
b. 交集JOIN
SELECT * FROM table1 AS a JOIN table2 b ON a.name=b.name
c. 差集NOT IN
SELECT * FROM table1 WHERE name NOT IN(SELECT name FROM table2)
d. 笛卡尔积
SELECT * FROM table1 CROSS JOIN table2
与
SELECT * FROM table1,table2相同
2. SQL中的UNION
UNION与UNION ALL的区别是,前者会去除重复的条目,后者会仍旧保留。
a. UNION
SQL Statement1
UNION
SQL Statement2
b. UNION ALL
SQL Statement1
UNION ALL
SQL Statement2
3. SQL中的各种JOIN
SQL中的连接可以分为内连接,外连接,以及交叉连接