合併查詢
子查詢
select field1,field2,…,fieldn
from tablename1 left
|right
[outer
]join tablename2
on condition;
左外連線select
*from student as a left
join class as b on a.class_id = b.id;
#左連線查詢所有學生對應的班級資訊
select
*from class as a left
join student as b on a.id = b.class_id;
#左連線查詢所有班級的學員資訊
右外連線select
*from student as a right
join class as b on a.class_id = b.id;
#右連線查詢所有班級對應的學員資訊
select
*from class as a right
join student as b on a.id = b.class_id;
#右連線查詢所有學員對應的班級資訊
union allselect id, teacher as people from class union
allselect class_id, name as people from student;
union使用比較運算子時,select 子句獲得的記錄數不能大於1條
select teacher from class where id=
(select class_id from student where name=
'小花'
);
in 的子查詢乙個查詢語句的條件可能落在另乙個select語句的查詢結果中,這時可以使用in關鍵字
select teacher from class where id in
(select class_id from student where name=
'小花');
select teacher from class where id in
(select class_id from student where name like
'小%'
);
exists 的子查詢exists 返回的是真或假
select
*from class where id=
102and
exists
(select
*from student where class_id=
102)
;
any 的子查詢關鍵字any表示滿足其中任一條件
select id, name, math+english+chinese total from grade where math+english+chinese >=
any(
select score from schoolarship)
;
all 的子查詢關鍵字all表示滿足所有條件
select id, name, math+english+chinese total from grade where math+english+chinese >=
all(
select score from schoolarship)
;
mysql聯合查詢
有乙個前提很重要 就是兩個表中的對應字段應該是建立聯合關係且該鍵應唯一 在查詢該聯合建的時候要指明 表.欄位 1.select from 表a,表a子表 where表a.filecode 表a子表.filecodeand表a.id in select 表a子表 id from 表a子表 where ...
MySQL聯合查詢
1.select test.name,test2.name2 from test left join test2 on test.id test2.id 2.select test.name,test2.name2 from test right join test2 on test.id test...
mysql聯合查詢
mysql聯合查詢效率較高,以下例子來說明聯合查詢 內聯 左聯 右聯 全聯 的好處 t1表結構 使用者名稱,密碼 userid int usernamevarchar 20 passwordvarchar 20 1 jack jackpwd 2 owen owenpwd t2表結構 使用者名稱,積分...