MySQL資料庫8 -子查詢,聯集查詢

來源:互聯網
上載者:User

標籤:

一 使用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 -子查詢,聯集查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.