練習:多表合併

多表合併

練習:多表合併

1.多表縱向合併union

MariaDB [hellodb]> select from teachers union select from students;

2.交叉連接

select from students cross join select from teachers;

3.內連接inner join

練習:多表合併
MariaDB [hellodb]> select * from students inner join teachers on students.teacherid=teachers.tid; 練習:多表合併

MariaDB [hellodb]> select stuid,s.name,tid,t.name from students s inner join teachers t on s.teacherid=t.tid;
練習:多表合併
MariaDB [hellodb]> select stuid,s.name,tid,t.name from students s,teachers t where s.teacherid=t.tid;
練習:多表合併

1)內連接後過濾數據

select stuid,s.name,tid,t.name from students s inner join teachers t on s.teacherid=t.tid and stuid >3;
練習:多表合併

4.左外連接

練習:多表合併
MariaDB [hellodb]> select stuid,s.name,tid,t.name from students as s left outer join teachers as t on s.teacherid=t.tid;

5.右外連接

練習:多表合併
MariaDB [hellodb]> select stuid,s.name,tid,t.name from students as s right join teachers as t on s.teacherid=t.tid;
練習:多表合併

6.左外連接擴展用法

練習:多表合併
MariaDB [hellodb]> select stuid,s.name,teacherid,tid,t.name from students as s left outer join teachers as t on s.teacherid=t.tid where t.tid is null;
練習:多表合併

7.完全外連接 full outer joion

練習:多表合併
select from students left join teachers on students.teacherid=teachers.tid
union
select
from students right join teachers on students.teacherid=teachers.tid;

子查詢:select 的執行結果,被其它SQL調用
select * from students where age < ( select avg(age) from students );
MariaDB [hellodb]> select stuid,name,age from students where age > (select avg(age) from students);
練習:多表合併

8.完全外連接的擴展示例

練習:多表合併
MariaDB [hellodb]> select * from (select s.stuid,s.name s_name,s.teacherid,t.tid,t.name t_name from students s left join teachers t on s.teacherid=t.tid union select s.stuid,s.name s_name,s.teacherid,t.tid,t.name t_name from students s right join teachers t on s.teacherid=t.tid) as a where a.teacherid is null or a.tid is null;
練習:多表合併

自連接
MariaDB [hellodb]> select emp.name emp_name , leader.name leader_name from employee emp inner join employee as leader on emp.leaderid=leader.id;
練習:多表合併

三張表連接示例
MariaDB [hellodb]> select st.stuid,st.name,sc.score,co.course from students as st inner join scores sc on st.stuid=sc.stuid inner join courses co on sc.courseid=co.courseid;
練習:多表合併

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章