文章目錄
- 1.聯合查詢
- 1.1笛卡爾積
- 1.2 內連接
- 1.3外連接
- 1.3.1 左外連接
- 1.3.2 右外連接
- 1.4自連接
- 1.5 子查詢
- 1.5.1單行子查詢
- 1.5.2多行子查詢
- 1.5.3 exists關鍵字
- 2.合并查詢
- 2.1 union
- 2.2 union all
1.聯合查詢
1.1笛卡爾積
實際開發中往往資料來自于不同的表,所以需要多表查詢,多表查詢是對多張表的資料取笛卡爾積,那么笛卡爾積是什么呢?

笛卡爾積:
先遍歷第一張表,依次取出表中的第一條記錄,再拿出這條記錄和第二張表再進行排列組合,
注意: 關聯查詢可以對關聯表取別名,
1.2 內連接
語法:
select 欄位 from 表1 別名1[inner] join 表2 別名2 on 連接條件 and 其他條件
select 欄位 from 表2 別名2 where 連接條件 and 其他條件;
(1)查詢"xuxian"同學的成績
select student.name,score.score,score.course_id
from student,score where student.name='xuxian'
and student.id=score.student_id;
select student.name,score.score,score.course_id
from student join score on student.name='xuxian'
and student.id=score.student_id;

(2)查詢所有同學的總成績,及學生的個人資訊
select student.name,student.id,score.student_id,sum(score.score)
from student,score
where student.id=score.student_id group by student.id;
select student.name,student.id,score.student_id,sum(score.score)
from student join score
on student.id=score.student_id group by student.id;

(3)查詢所有同學的成績,及同學的個人資訊
select student.id,student.name,course.name, score.score
from student,course, score
where student.id=score.student_id
and course.id=score.course_id;

1.3外連接
外連接分為左外連接和右外連接,如果聯合查詢,左側的表完全顯示的我們稱為左外連接;右側完全顯示我們就稱為右外連接,
假設有兩張表,此時學生表中的王五,在分數表中沒有成績,分數表中4,在學生表中沒有學生存在,

1.3.1 左外連接
-- 左外連接,表1完全顯示
select 欄位名 from 表1 left join on 表2 on 連接條件;
--示例
select student.name, student.id,score.score from student left join on student.id=score.student_id;

1.3.2 右外連接
-- 右外連接,表2完全顯示
select 欄位名 from 表1 right join on 表2 on 連接條件;
--示例
select student.name, student.id,score.score from student right join on student.id=score.student_id;

1.4自連接
自連接是指在同一張表連接自身進行查詢,
顯示所有的“計算機原理”成績比“Java成績高的成績資訊”
select * from score s1,score s2
where s1.student_id=s2.student_id
and s1.course_id=1
and s2.course_id=3
and s1.score<s2.score;

1.5 子查詢
子查詢是指嵌入到其他sql陳述句中的select陳述句,也叫做嵌套查詢,
1.5.1單行子查詢
單行子查詢:回傳一行記錄的子查詢,
查詢于“buxiaobiye"的同班同學:
select name from student where
classes_id=
(select classes_id from student
where name='buxiangbiye');

1.5.2多行子查詢
多行子查詢:回傳多行記錄的子查詢
查詢"english"或“chinese"課程的成績資訊,
select * from score
where score.course_id in
(select id from course
where name='chinese' or name='english');

1.5.3 exists關鍵字
select * from score
where exists
(select score.course_id from course
where(name='chinese' or name='english')
and course.id=score.course_id);

exists:一邊進行外層查詢,一邊進行里查詢.
在from子句中使用子查詢:子查詢陳述句出現在from子句中,這里要用到資料查詢的技巧,把一個子查詢當作一個臨時表可以使用,
2.合并查詢
在實際開發中,為了合并多個select執行的結果,可以把使用集合運算子union,union all.使用union和union all時,前后查詢的結果集中,欄位需要一致,
2.1 union
該運算子用于取得兩個結果的并集,當使用該運算子時,會自動去掉結果集中的重復行,
查詢id<3,或者名字為"english"的課程:
select * from course where id<3
union
select * from course where name='english';

2.2 union all
該運算子用于取得兩個結果集的并集,當使用該運算子時,不會去掉結果中的重復行,
示例:查詢id小于3,或者名字為"java"的課程
select * from course where id<3
union all
select * from course where name='java';
可以看到結果中Java出現了兩次,沒有去掉重復行,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277815.html
標籤:其他
上一篇:Hadoop MapReduce 框架原理 | InputFormat 資料輸入
下一篇:Redis——Redis的事務
