1. 程式人生 > >資料庫之連線查詢

資料庫之連線查詢

 學生表

CREATE TABLE student ( stuid VARCHAR (10) PRIMARY KEY, stuname VARCHAR (50) );

 分數表

CREATE TABLE score ( stuid VARCHAR (10), score INT, courseid INT );

 科目表

CREATE TABLE course ( courseid VARCHAR (10) PRIMARY KEY, cname VARCHAR (50) );

合併查詢 把兩張表的記錄合併在一起列印 
union取兩張表交集 必須是欄位名和 資料型別相同

SELECT * FROM a UNION SELECT * FROM b;

SELECT * from a,b;出現了大量重複資料
笛卡爾積

SELECT * FROM a, b;

測試一下分數表和學生表一起查詢

SELECT * FROM student, score;

去除重複資料(99查詢法 通過兩張表關聯欄位相等 來去除)

SELECT * FROM student, score WHERE student.stuid = score.stuid;

查詢學生編號和學生的分數

SELECT student.stuid, score.score FROM student, score WHERE student.stuid = score.stuid;

給表起別名

SELECT s.stuname, sc.score FROM student s, score sc WHERE s.stuid = sc.stuid;

多表查詢時不一定非要有外來鍵
學生表和分數表和科目表一起查

SELECT s1.stuid, s1.stuname, s2.score, s2.courseid, c.cname FROM student s1, score s2, course c WHERE s1.stuid = s2.stuid AND s2.courseid = c.courseid;

查詢學生的名字和對應分數和科目

SELECT s1.stuname, s2.score, c.cname FROM student s1, score s2, course c WHERE s1.stuid = s2.stuid AND s2.courseid = c.courseid;

查詢表中80分以上學生的 姓名 分數 科目資訊

SELECT s1.stuname, s2.score, c.cname FROM student s1, score s2, course c WHERE s1.stuid = s2.stuid AND s2.courseid = c.courseid AND s2.score > 80;

連線查詢
內連線 外連結 自然連線
內連線 表一 inner(可以省略) join 表二 on 去除重複條件

SELECT * FROM student s JOIN score sc ON s.stuid = sc.stuid;

SELECT * FROM student s JOIN score sc ON s.stuid = sc.stuid JOIN course c ON sc.courseid = c.courseid WHERE sc.score > 80;

外連結
左外連結LEFT OUTER(可以省略) JOIN 左邊那張表為主 會輸出這個表的全部資料
右外連結RIGHT JOIN

SELECT * FROM student s LEFT JOIN score sc ON s.stuid = sc.stuid;

SELECT * FROM student s RIGHT JOIN score sc ON s.stuid = sc.stuid;

自然連線 
自動匹配表中關聯匹配

SELECT * FROM student NATURAL JOIN score;