Ji Chang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 資料庫教學簡報 # 簡報的名稱 tags: DB, database # 簡報的標籤 slideOptions: # 簡報相關的設定 theme: solarized # 顏色主題 transition: 'fade' # 換頁動畫 --- # 資料庫 基本上我都教如何使用 mysql 但其實資料庫都一樣啦,除了各式資料庫有些特殊的語法與型別之外 ---- 線上問題提問 https://app.sli.do/event/bglqmplb ![](https://i.imgur.com/cyxOF8J.png) --- # 安裝 MySQL ---- https://downloads.mysql.com/archives/installer/ 選擇 Archived Versions 版本 5.7.29 Windows (x86, 32-bit), MSI Installer (mysql-installer-community-5.7.29.0.msi) ---- ![](https://i.imgur.com/TMEd4ts.png) ---- ![](https://i.imgur.com/SRrDIEd.png) ---- ![](https://i.imgur.com/HYJlGC4.png) ---- ![](https://i.imgur.com/ypYKLHO.png) ---- ![](https://i.imgur.com/sOgKAeX.png) ---- ![](https://i.imgur.com/RkDLeg0.png) ---- ![](https://i.imgur.com/O3G4NGt.png) ---- ![](https://i.imgur.com/SQAfFom.png) ---- ![](https://i.imgur.com/YonPsAr.png) ---- ![](https://i.imgur.com/r6toB8c.png) ---- ![](https://i.imgur.com/BoXzUQp.png) ---- ![](https://i.imgur.com/20EO7I2.png) ---- ![](https://i.imgur.com/2x07u5p.png) ---- ![](https://i.imgur.com/CipK5Y9.png) ---- ![](https://i.imgur.com/hCrXaEK.png) ---- ![](https://i.imgur.com/25kx2Oi.png) ---- ![](https://i.imgur.com/CuraEXN.png) ---- ![](https://i.imgur.com/Oc4jJwV.png) ---- ![](https://i.imgur.com/0ge76Wn.png) ---- ![](https://i.imgur.com/N0TPi3D.png) ---- ![](https://i.imgur.com/xMNKqB6.png) ---- ![](https://i.imgur.com/ewgJ4je.png) ---- ![](https://i.imgur.com/im2JeAV.png) ---- ![](https://i.imgur.com/DH7MPqJ.png) ---- ![](https://i.imgur.com/TLhjHGs.png) ---- 下載 SQL 檔案並匯入 https://drive.google.com/file/d/0B4xPn1yagKirQUtMU2lITncyOTQ/view ---- ![](https://i.imgur.com/ELLQaTt.png) ---- ![](https://i.imgur.com/PlEr0RS.png) ---- ![](https://i.imgur.com/douVyKd.png) ![](https://i.imgur.com/3XK1qvr.png) ---- 環境準備工作完成 ---- ![](https://i.imgur.com/v3EpbDa.png) --- # SQL 基礎 ---- ## 表格、紀錄與欄位 表格是資料庫的基礎,由欄位組合而成的,儲存在表格中的每一筆紀錄就擁有這些欄位的資料。 以儲存城市資料(city)來說,設計表格的人認為此資料需要包含編號、名稱、國家代碼、區域和人口數量,所以為 city 表格設計了這些欄位(column) ---- 而儲存在表格中的每一筆資料稱為「列(row)」或「紀錄(record)」: ---- 設計表格時,通常會指定一個欄位為「主索引鍵(primary key)」,是唯一的 大部份時候都是設定自動遞增的整數 ---- ## 資料型態 跟程式語言一樣,資料庫中可以儲存各種不同的資料,SQL也提供許多不同的「資料型態」。 ---- 第一種是數值,為了更精準的保存數值資料,SQL提供整數與小數兩種數值型態 ---- 還有「字串」與「日期」 在SQL敘述中使用字串、日期資料的時候,字串、日期資料的前後要使用單引號或雙引號「`'`」 「`"`」 ---- 另外一種在資料庫中比較特殊的資料型態是「NULL」,是用來表示「沒有」的資料。 --- # SELECT 查詢敘述 在執行資料庫的操作中,查詢算是最常見也是最複雜的工作 ---- 下列是查詢敘述的基本語法: ```SQL= SELECT [...] FROM [...] WHERE [...] GROUP BY [...] HAVING [...] ORDER BY [...] LIMIT [...] ``` 使用「SELECT」搭配各種子句來查詢時,要特別注意子句使用的順序 ---- ## 只有SELECT ```SQL= SELECT 'NCYU', 1+1 ``` 這樣的用法跟資料庫一點關係都沒有,它只不過把你輸入的內容顯示出來而已 但有時候很好用w ---- ## 指定欄位與表格 一般查詢敘述,查詢資料表中的資料 所以「SELECT」會搭配「FROM」來使用, 而「SELECT」後面可以指定「*」表示要查詢指定表格的所有欄位 ```SQL= SELECT * FROM world.city ``` ---- ## 指定需要的欄位 有時候並不需要查詢一個表格中所有的欄位,可以在「SELECT」後面自己指定需要的欄位 ```SQL= SELECT Name, ContryCode FROM city ``` ---- ## 數學運算 | 優先序 | 運算子 | 說明 | 範例 | 結果 | | --- | --- | --- | --- | --- | | 1 | % | 餘數 | 7 % 3 | 1 | | 1 | * | 乘 | 7 * 3 | 21 | | 1 | / | 除 | 7 / 3 | 2.333 | | 1 | DIV | 除(整數)| 7 DIV 3 | 2 | | 2 | + | 加 | 7 + 3 | 10 | | 2 | - | 減 | 7 – 3 | 4 | ---- ## 別名 ```SQL= SELECT Name, CountryCode AS CC FROM world.city ``` 通常一般欄位取別名是比較沒必要的。 如果是運算式的話,通常就要幫它取一個欄位別名來取代原來一大串的運算式。 像是計算人口密度 ```SQL= SELECT Population/SurfaceArea AS PopulationDensity FROM word.country ``` ---- ## 條件查詢 資料庫最大的好處就是可以隨時依照需要查詢部份紀錄資料,你可以搭配「WHERE」子句執行查詢條件的設定 ```SQL= SELECT * FROM city WHERE CountryCode='TWN' ``` ---- ### 比較運算子 要使用「WHERE」執行查詢條件的設定,會使用下列基礎的比較運算子: | 運算子 | 說明 | | --- | --- | | = | 等於 | | != | 不等於 | | < | 小於 | | <= | 小於等於 | | > | 大於 | | >= | 大於等於 | ---- 可以執行以下命令,看會出現什麼結果 ```SQL= SELECT * FROM city WHERE Population < 800 ``` 意義? ```SQL= SELECT * FROM city WHERE Population <= 8000 ``` ---- ### 邏輯運算子 條件設定,有時候並不會太複雜;不過很常遇到在一個查詢的需求中,需要一個以上的條件 | 優先順序 | 運算子 | 說明 | | --- | --- | --- | | 1 | NOT | 非 | | 2 | && | 而且 | | 2 | AND | 而且 | | 3 | \|\| | 或 | | 3 | OR | 或 | | 3 | XOR | 互斥 | ---- 如果想要查詢國家代碼是「TWN」,而且人口數量小於十萬的城市? ```SQL= SELECT * FROM city WHERE Population <= 100000 AND CountryCode = 'TWN' ``` ---- 小練習: * 如果想要查詢國家代碼是「USA」,而且人口數量小於 200000 的城市? * 如果想要查詢國家代碼是「USA」或「TWN」的城市? * 如果想要查詢國家代碼是「USA」或「TWN」的城市,並且人口要小於十萬人? ---- 檢查一下第3個練習的結果,看是不是所以的人口都小於十萬人呢? 如果不是,看看哪裡做錯了! ---- 如果查詢條件中,有「AND」和「OR」同時出現的話,就要依照你的需要,視情況加上左右刮號來控制條件的設定,因為在邏輯運算子的介紹中,它們也同樣有「優先順序」的。 ---- ### 其它條件運算子 * BETWEEN … AND …:範圍比較 * IN (…):成員比較 * IS:是… * IS NOT:不是… * LIKE:像… ---- #### BETWEEN … AND … ```SQL= SELECT * FROM city WHERE Population >= 100000 AND Population <= 110000 ``` 等價於 ```SQL= SELECT * FROM city WHERE Population BETWEEN 100000 AND 110000 ``` 有沒有比較好懂呢? ---- #### IN ```SQL= SELECT * FROM city WHERE CountryCode = 'TWN' OR CountryCode = 'USA' OR CountryCode = 'JPN' ``` 等價於 ```SQL= SELECT * FROM city WHERE CountryCode IN ('TWN', 'USA', 'JPN') ``` 一樣有更好懂嗎? ---- ### 字串樣式 ```SQL= SELECT * FROM city WHERE Name = 'w' ``` 上面這段命令是啥意思? ---- 那如果我要 w 開頭的城市名稱呢? ```SQL= SELECT * FROM city WHERE Name LIKE 'w%' ``` 上列語法中,在「LIKE」後面的「樣版」字串中,會使用到下列兩種「樣版字元」: * % :0到多個任何字元 * _ :一個任何字元 ---- ```SQL= SELECT * FROM city WHERE Name LIKE 'w%' ``` 上列的查詢條件中 「w%」表示第一個字元是「w」就符合條件 「%w」表示最後一個字元是「w」就符合條件 最後一個「%w%」表示不論在什麼位置有「w」字元,都符合條件 ---- #### 小練習 * 如果想要查詢國家代碼是「TWN」的城市,且名稱是「T」開頭呢? * 如果想要查詢國家代碼是「USD」或「JPN」的城市,且名稱是「S」開頭5個字母的城市呢? * 如果想要查詢國家代碼是「USD」或「JPN」的城市,且名稱是「P」開頭、人口在 200000 ~ 300000 之間呢? ---- ## 排序 一般的查詢通常會有資料排序上的需求,所以你會使用「ORDER BY」子句 ---- 如果想要查詢時依照人口數量排序的話 ```SQL= SELECT * FROM city ORDER BY Population ``` 以上是由小到大,當然可以由大到小 ```SQL= SELECT * FROM city ORDER BY Population DESC ``` ---- 當然我們可以用兩個以上的欄位做排序 比方說先依照國家代碼的名稱做字典排序、在依照人口由大到小排序 ```SQL= SELECT * FROM city ORDER BY CountryCode, Population DESC ``` 備註:在 MySQL 5.6 之後,不能使用沒有被 Select 的出來做排序 ---- ## 限制查詢 使用「LIMIT」子句指定回傳紀錄的數量,像是一般論壇的分頁 * LIMIT 10 :回傳前十筆資料 * LIMIT 100, 10 :跳過一百筆之後回傳前十筆資料 輸出USA中前3個最常用的語言 ```SQL= SELECT * FROM CountryLanguage WHERE CountryCode = 'USA' ORDER BY Percentage DESC LIMIT 3 ``` ---- ## 排除重複紀錄 在一個查詢敘述執行以後,資料庫不會幫你檢查回傳的資料是否重複(回傳的兩筆紀錄資料完全一樣) 但可以在「SELECT」子句後面可以讓你設定「回傳的資料是否重複」 輸出不重複的各大洲 ```SQL= SELECT DISTINCT Continent FROM country ``` ---- #### 小練習 * 輸出不重複的各種語言名稱 (從CountryLanguage表格中取出) * 輸出國土面積前十大的國家 * 輸出亞洲人口最少的第 11 ~ 15 個國家 --- # Group 有時間再說... ---- 群組函式可以很容易的查詢需要的統計與分析資訊: * MAX(運算式):最大值 * MIN(運算式):最小值 * SUM(運算式):合計 * AVG(運算式):平均 * COUNT([DISTINCT]\*|運算式) 以上可以直接用,會把整個Table是做一個Group ---- ## GROUP BY 可以根據欄位的內容進行分組 像是 根據洲名取該洲的總人數 ```SQL= SELECT Continent, SUM(Population) AS Population_sum FROM country GROUP BY Continent ``` 根據地區取地區的總人數 ```SQL= SELECT Region, SUM(Population) AS Population_sum FROM country GROUP BY Region ``` ---- ## HAVING 在一般的查詢中,查詢條件在 WHERE 就好, 但經過 Group 運算式計算過後的值,就得使用 HAVING ---- 像是要取得所有地區總人口超過十億的 ```SQL= SELECT Region, SUM(Population) Population_sum FROM country GROUP BY Region HAVING Population_sum > 1000000000 ``` --- # JOIN ## 使用多個表格 ---- 在「world」資料庫的「country」表格中,儲存世界上所有的國家資料,其中有一個欄位「Capital」用來儲存首都資料,不過它只是儲存一個編號; 另外在「city」表格中,儲存世界上所有的城市資料,它主要的欄位有城市編號和城市的名稱: ---- ## Inner Join 有兩種方式可以使用 1. Where 中 2. From 中 ---- ### Where 中 ```SQL= SELECT country.Code, country.Capital, city.Name FROM country, city WHERE country.Capital = city.id ``` ---- ### FROM 中 ```SQL= SELECT country.Code, country.CApital, city.Name FROM country INNER JOIN city ON country.Capital = city.id ``` --- # CRUD 資料庫當然不只查詢,增、修、刪也是很重要的 ---- ## Insert 新增資料 ```SQL= INSERT [INTO] 表格名 VALUE (資料, ...) ``` 注意這種方法資料塞入的順序要與定義時的順序一樣 ---- ## Insert 新增資料2 ```SQL= INSERT [INTO] 表格名 [(欄位名稱, ...)] VALUE (資料, ...) ``` 這種方法就要依照自己定義的欄位順序,沒有指定的欄位就會自動塞入 NULL ---- 舉個例子,嘉義大學變成所謂的學園都市了(? Example: ```SQL= INSERT INTO `city` (`Name`, `CountryCode`) VALUES ('NCYU','TWN') ``` ---- 也因為這樣的規定,所以有些新增敘述在語法上雖然沒有錯誤,如果違反表格設計上的規定,同樣會造成錯誤 ---- ## Update 修改 ```SQL= UPDATE 表格名稱 SET 欄位名稱=(運算式|資料) [, ...] ``` ---- 使用「UPDATE」敘述的時候,通常會搭配使用「WHERE」子句,用來指定要修改的紀錄 ```SQL= UPDATE 表格名稱 SET 欄位名稱=(運算式|資料) [, ...] WHERE [條件] ``` 注意,如果你忘記了 WHERE 的話,會把所有的紀錄全部一起修改 ---- 舉個例子,現在台灣人口大爆炸好了,你要把台灣的人口改成 1 億,要怎處理 ```SQL= UPDATE `country` SET Population=100000000 WHERE `Code`='TWN' ``` ---- 舉個例子2,現在海平面上升,每個國家土地都減少了 1/5 ,那該如何更新? ```SQL= UPDATE `country` SET SurfaceArea=SurfaceArea*0.8 ``` ---- ## Delete 刪除 ```SQL= DELETE FROM 表格名稱 [WHERE 條件] ``` 使用「DELETE」敘述的時候,通常會搭配使用「WHERE」子句,用來指定要修改的紀錄 注意,如果你忘記了 WHERE 的話,會把所有的紀錄全部一起刪除 ---- 一樣舉個例子,學園都市要合併回嘉義市,那如何把剛剛新增的資料刪除。 ```SQL= DELETE FROM `city` WHERE Name='NCYU' ``` 要注意的是,如果有很多 Name 都叫 NCYU 就都會一起被刪除喔~~ ---- 小練習: 1. 幫台灣多新增幾個城市吧 2. 現在世界人口爆炸,每個國家的人口都變成現在人口的 1.4 倍呢? 3. 因海平面上升 小國家被淹沒滅國了(?),請刪除土地面積小於 10000 國家 提示:刪除前可以使用 SELECT 來看看要刪除的資料,以免下錯指令喔 --- END~~ ---- REF: [MySQL超新手入門- 張益裕](https://books.google.com.tw/books?id=dYFLBAAAQBAJ&printsec=frontcover&dq=MySQL%E8%B6%85%E6%96%B0%E6%89%8B%E5%85%A5%E9%96%80&hl=zh-TW&sa=X&ved=0ahUKEwiCrrPBkNTpAhUwBKYKHSJ6De4Q6AEIKDAA#v=onepage&q=MySQL%E8%B6%85%E6%96%B0%E6%89%8B%E5%85%A5%E9%96%80&f=false) ---- 下課回家啦

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully