1. 程式人生 > 其它 >回顧MySQL查詢語句經典例項1

回顧MySQL查詢語句經典例項1

技術標籤:MySQLJava Web技術解析MySQL

#1.查詢" 01 "課程比" 02 "課程成績高的學生的資訊及課程分數
#分析:由於需要查詢學生的全部資訊,所以需要從分數表中查詢到符合條件的分數,然後通過left join/right join進行組合
#右連線

select * from student RIGHT JOIN (
  select t1.sid, courseA, courseB 
    from
    (SELECT sid, score as courseA FROM score WHERE score.cid = '01') as t1,
    (SELECT sid, score as courseA FROM score WHERE score.cid = '02') as t2
  where t1.sid = t2.sid and t1.coureA > t2.courseB
)r
on student.sid = r.sid;

#左連線

select * from (
  select t1.sid, courseA, courseB
  from
    (SELECT sid, score as courseA FROM score WHERE score.cid = '01') as t1,
    (SELECT sid, score as courseA FROM score WHERE score.cid = '02') as t2
  where t1.sid = t2.sid and t1.coureA > t2.courseB
) r
LEFT JOIN student
ON student.sid = r.sid;

#查詢同時存在“01”課程和“02”課程的情況

select * from
  (select * from score where score.cid = '01') as t1,
  (select * from score where score.cid = '02') as t2
where t1.sid = t2.sid;

#查詢存在"01"課程但可能不存在"02"課程的情況(不存在顯示null)
#這一道就是明顯需要使用join的情況了,02可能不存在,即為left join的右側或right join 的左側即可
#左連線

select * from
(select * from score where score.cid = '01') as t1
left join
(select * from score where score.cid = '02') as t2
on t1.sid = t2.sid;

#右連線

select * from
(select * from score where score.cid = '02') as t2
right join
(select * from score where score.cid = '01') as t1
on t1.sid = t2.sid;

#查詢不存在" 01 "課程但存在" 02 "課程的情況

select * from score
where score.sid not in (
  select sid from score
  where score.cid = '01'
)
AND score.cid= '02';

暫時先總結到這裡,待續......