join查詢


1.  join查詢

1.1.  建表語句

drop table if exists student_course;

drop table if exists course;

drop table if exists student;

 

 

create table course(

       cid int not NULL,

       cname varchar(20) not null,

       constraint pk_cid primary key(cid)

);

 

create table student(

    sid int not null,

    sname varchar(20),

    constraint pk_sid primary key(sid)

);

 

create table student_course(

    m_sid bigint not null,

    m_cid bigint not null,

    constraint pk_sid_cid primary key(m_sid,m_cid),

    constraint fk_sid foreign key(m_sid) references student(sid) ,

    constraint fk_cid foreign key(m_cid) references course(cid)

);

 

insert into student values(1,'張三'),(2,'李四'),(3,'王五'),(4,'麻子');

insert into course values(1,'高等數學'),(2,'大學英語'),(3,'大學物理'),(4,'電影欣賞');

insert into student_course values (1,2),(1,4),(2,4),(3,4);

 

select * from student;

select * from course;

select * from student_course;

 

1.2.  笛卡爾集,結果有64條 4*4*4

select * from course, student, student_course;

1.3.  內連接,求兩個表的交集。

可以不指定inner,默認就是inner join。

select * from student_course inner join course on (m_cid = cid);

1.4.  左外連接

用法: a left join b on(a.id=b.id) 或者 a left join b using(id)。a的所有列均出現在結果中,b的數據被連接進來,無連接項的則顯示為空,多連接項的在新行展示

select * from student left join student_course on(m_sid=sid);

 

select * from student left join student_course on(m_sid=sid) left join course on(m_cid=cid);

1.5.  右外連接

select * from student right join student_course on(m_sid=sid);

select * from student right join student_course on(m_sid=sid) right join course on(m_cid=cid);

 

1.6.  全外連接

用法: a full outer join b on(a.id=b.id) 或者 a full outer join b using(id). 其中outer可以省略。實際是一個內連接加上左表和右表獨有的數據行,左表獨有的行右表字段填充NULL

select * from student full join student_course on(m_sid=sid);

select * from student full join student_course on(m_sid=sid) full join course on(m_cid=cid);

UNION,INTERSECT和EXCEPT(並集,交集,差集)

參考文章: https://www.cnblogs.com/alianbog/p/5621562.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM