
join on 與數學原理
pgsql切換數據庫 直接輸入 \C youdatabasename 即可 \d 表名 —— 得到表結構 select * from tablename查看表的數據
相信有不少人讀一遍兩邊都不懂,
A集合有n行,x列,B集合有m行,y列 那么笛卡爾之積就是 一個(m*n)行,(x+y)列
把復雜的問題簡單化,把深奧的問題通俗化,那就是教育家,哈哈哈請叫我教育家:
create table tbl_course( course_id bigint not null primary key, course_name varchar(12) not null ); create table tbl_student( stu_id bigint not null, stu_name varchar(12), constraint pk_tbl_student_stu_id primary key(stu_id) ); create table tbl_student_course( stu_id bigint not null, course_id bigint not null, constraint pk_tbl_student_course_stu_id_course_id primary key(stu_id,course_id), constraint fk_tbl_student_course_stu_id foreign key(stu_id) references tbl_student(stu_id) , constraint fk_tbl_student_course_course_id foreign key(course_id) references tbl_course(course_id) );
插入測試數據: insert into tbl_course values(1,'高等數學'),(2,'大學英語'),(3,'大學物理'),(4,'電影欣賞'); insert into tbl_student values(1,'張三'),(2,'李四'),(3,'王五'),(4,'麻子'); insert into tbl_student_course values (1,2),(1,4),(2,4),(3,4);
select * from tbl_course ,tbl_student,tbl_student_course;//笛卡爾之積

沒有什么意義,因為只有四條數據,除非加上分組,去重才會有意義
二.內連接 JOIN連接分為內連接和外連接,而外連接又分為左外連接,右外連接,全外連接。


內連接只要中間那一部分
三.左外連接 左外連接其實是一個內連接然后加上左表獨有的數據行,結果集中右表的字段自動補充NULL。 LEFT OUTTER JOIN ,其中OUTER可以省略。

select * from tbl_student left join tbl_student_course using(stu_id) left join tbl_course using(course_id);
//以左邊學生為准,包括未選課的4號學生麻子

四.右外連接 右外連接其實是一個內連接然后加上右表獨有的數據行,結果集中左表的字段自動補充NULL。

RIGHT OUTTER JOIN ,其中OUTER可以省略。
//以右邊的表為准,左邊不足的為空,和mysql很相似

五.全外連接 全外連接其實是一個內連接然后加上左表和右表獨有的數據行,左表獨有的數據行右表的字段補充NULL,右表獨有的數據行左表字段補充NULL。


查詢沒有選課的學生:


查詢只在右表中存在的數據
查找沒有被選擇的課程


查詢沒有選課的學生和沒有被選的課程

就是三表聯查 選擇彼此都沒有的那部分
