標籤:
一 使用IN關鍵字的子查詢
問題: 查詢遊戲類型是‘棋牌類‘ 的遊戲的分數資訊
- 遊戲分數表中並未包含遊戲類型資訊
思路一:採用連結查詢
思路二: 分兩步進行,首先找到所以‘棋牌類‘遊戲的編號,再以這一組編號為查詢依據完成查詢
select * from scores where gno in (select gno from games where gtype =‘棋牌‘)
例:查詢沒有參與5號遊戲的玩家QQ
select user_qq from users where user_qq not in (select user_qq from scores where gno=5)
二 使用exists 關鍵字的子查詢
例:如果存在暱稱為‘孫悟空’,則查詢分數表中的資料
select * from scores where exists (select * from users user_name =‘孫悟空‘)
三 聯集查詢
select _statement union[all] select_statement [union[all] select_statement][...n]
作用與特點:可以把多條查詢語句所產生的結果集縱向串連為一體
有ALL關鍵字可以顯示全部資料(即重複的也顯示出來)
列的數量與類型都要相容
select user_name from users
union
select gname from games
例:查詢玩家表中所有女性玩家和生日為空白的玩家
select * from users where user_sex=‘女‘
union
select * from users where user_birthday is null
<<=====>> select * from users where user_sex=‘女‘ or select * from users where user_birthday is null
例:查詢qq號是‘12302’的玩家所有分數並計算出總分數和平均分數,並顯示到同一結果集中
select user_qq,gno,score from scores where user_qq=‘12302‘ union all select ‘總分‘,‘ ‘,sum(score) from scores union all select ‘平均分‘,‘ ‘,avg(score) from scores where user_qq=‘12302‘
MySQL資料庫8 -子查詢,聯集查詢