SlideShare uma empresa Scribd logo
1 de 38
MySQL

Ensky / 林宏昱
Why Database
你也可以選擇用fopen + CSV土法煉鋼,但很快的
你會遇到很多很多問題…

林宏昱,小天,資工系,交通大學
張哲彬,變態,資工系,交通大學

你會發現,當多一點使用者的時候,兩個使用者
同時註冊/發表文章的時候你的資料就會毀掉。
Why Database
flock!
沒錯,但以檔案為基礎的管理方式,速度非
常的慢,若純用檔案可能使用者100人就會花
很多時間在等待開鎖解鎖上了。

還有很多很多問題阿,比如說你突然要新增
一個欄位email此時用檔案系統的情況下,你
需要每一行都打開來檢查
Why Database
上面提到都是架構面的,而實際上使用者會
需要對資料庫問一些奇怪的問題:
• 找出鳥彬的學期成績
這還好,怕的是
• 找出鳥彬平均 >90 的學期,最高的三門科
  目的教授們,他們的實驗室同學有哪些

這種問題就需要關聯式資料庫來幫你囉!
Database Management System
Common DBMS
• 免費
• 功能完整
• 普及(大家都在用)




• 我很熟…XD
phpMyAdmin
phpMyAdmin
由於Console的操作方式實在不直覺
因此有人用PHP寫出一套管理MySQL的網站
叫做phpMyAdmin

直接解壓縮到網頁根目錄就可以用了:P
Architecture
• 一台DB server可以開很多個database
  (一個project一個database這樣)

• 一個database可以有很多table
  (ex: user, forum, …)

• 一個table可以有很多column
  (ex in user: name, sex, email, password, …)
行&列
姓名        性別         綽號
林宏昱       Boy        小天
張哲彬       ?          啪啪啪
吳孟謙       女          腦b


Table 的基礎,就是行(column)與列(row)
column代表不同的類別,
row代表一列一列的資料。
資料型態 (DataType)
•   INT        123
•   VARCHAR    abcd
•   TEXT       “這是有很多字的文章”
•   DATE       2012-08-15
•   DATETIME   2012-08-15 14:00:00
•   BINARY     010101010111110001
•   ENUM       單選
•   SET        複選
Live Demo : Create table
索引 ( index )
Database有一個技術,叫做index,
當一個table的某個column被加上了index之後,
他會被database建立索引,
用他找資料會很快。

比如說有個table user: stdid, name, sex, email
我在學號上建立索引,
就可以很快的用學號找到人。
索引 ( index )
索引有分以下類別
• Primary key (主鍵)
 資料中最具有代表性的一個欄位,唯一
 ex: user中的學號
 特性:一定要有值、唯一
• Unique key (唯一鍵)
 毫無反應,唯一的索引
• Index (索引鍵)
 毫無反應,不唯一的索引
索引 ( index )
當設定成Primary key的時候,會有一個功能可
以用,就是Auto Increment。

有時候你可能會給每個user一個編號(id),第
一個user編號是1,第二個編號是2,以此類推。

此時就可以將id這個column設定成primary key,
並且讓他有auto increment功能,此時每插入
一筆新的user,id就會自動是max(id) + 1
Live Demo : Setting Index
關聯
有些時候,Table之間會有一些關係
user
id        username    name         nickname
1         ensky       林宏昱          小天
2         Jalex       張哲彬          啪啪啪
3         fancy0305   羅宛琪          重訓一姊


user_skill
user_id   blood       skill        power
1         100         寫網頁          150
2         200         爆肝           100
3         50          重訓           10000
關聯
    有些時候,Table之間會有一些關係
               User                                          Skill
id   username    name     nickname              id   name   attack   defense
1    ensky       林宏昱      小天                    1    寫網頁    50       50
2    Jalex       張哲彬      啪啪啪                   2    爆肝     -50      -50
3    fancy0305   羅宛琪      重訓一姊                  3    重訓     1000     1000



                               user_id   skill_id
                                 1          1
                                 1          2
                                 2          2
             user_skill          3          2
                                 3          3
關聯
我們可以藉由設定foreign – key來建立兩個
table之間的關係

條件:
• 要建立關係的兩個column都必須是index
• 引擎必須是InnoDB
Live Demo: foreign key setting
Structured Query Language
SQL是一個很特別的語言,他是專門設計來操
作DBMS的。

主要的操作方式,有Select(讀出來)、
Update(更新)、Insert(插入資料)、Delete(刪除)

不同的DBMS,SQL語句會有點小小的不同,
但都大同小異,一個通其他的也會通。
Insert
INSERT INTO `user` (`name`, `nick`)
VALUES
("林宏昱", "天天"),
("張哲彬", "啪啪啪")
Select
                 user
id   username     name   nickname
1    ensky        林宏昱    小天
2    Jalex        張哲彬    啪啪啪            username

3    fancy0305    羅宛琪    重訓一姊           ensky
                                        Jalex
SELECT * FROM `user`                    fancy0305

SELECT `username` FROM `user`
SELECT `id`, `username` FROM `user`
id   username
1    ensky
2    Jalex
3    fancy0305
Select Order By
                 user
id   username     name   nickname
1    ensky        林宏昱    小天
2    Jalex        張哲彬    啪啪啪
3    fancy0305    羅宛琪    重訓一姊
                                    id        username      name    nickname
SELECT * FROM `user`                1         ensky         林宏昱     小天

ORDER BY username                   3         fancy0305     羅宛琪     重訓一姊
                                    2         Jalex         張哲彬     啪啪啪


SELECT * FROM `user`                     id     username     name    nickname
                                         2      Jalex
ORDER BY username DESC                                       張哲彬     啪啪啪
                                         3      fancy0305    羅宛琪     重訓一姊
                                         1      ensky        林宏昱     小天
Select Where
                 user
id   username     name   nickname
1    ensky        林宏昱    小天
2    Jalex        張哲彬    啪啪啪
3    fancy0305    羅宛琪    重訓一姊

SELECT name FROM `user`
                                        name
WHERE `username` = "ensky"              林宏昱


SELECT username, nickname FROM `user`
WHERE `username` = "ensky"
                             username nickname
OR `username` = "Jalex"      ensky    小天
                                    Jalex      啪啪啪
Select Limit
                           id    username     name    nickname
SELECT * FROM `user`       1     ensky        林宏昱     小天
                           2     Jalex        張哲彬     啪啪啪
                           3     fancy0305
SELECT * FROM `user`
                                              羅宛琪     重訓一姊

                       id       username     name    nickname
LIMIT 1
                       1        ensky        林宏昱     小天

SELECT * FROM `user`   id       username     name    nickname
LIMIT 1, 2             2        Jalex        張哲彬     啪啪啪
                       3        fancy0305    羅宛琪     重訓一姊

SELECT * FROM `user`
                       id       username     name    nickname
LIMIT 2, 1             3        fancy0305    羅宛琪     重訓一姊
Select Join
                                                          User
  SELECT *                                  id    username        nickname
  FROM `user_skill`                         1     ensky           小天
  JOIN User                                 2     Jalex           啪啪啪

  ON User.id = user_skill.id                3     fancy0305       重訓一姊                 Skill
                                                                                  id    name

user_id   skill_id User.   User.       User.                                      1     寫網頁
                   id      username    nickname            user_skill             2     爆肝
  1         1      1       ensky       小天                  user_id     skill_id   3     重訓
  1         2      2       Jalex       啪啪啪                    1           1

  2         2      2       Jalex       啪啪啪                    1           2

  3         2      3       fancy0305   重訓一姊                   2           2

  3         3      3       fancy0305   重訓一姊                   3           2
                                                              3           3
Select Distinct                user1
                                     username    nickname
                                     ensky       小天
假設現在我想撈unique的
                                     Jalex
username
                                                 啪啪啪
                                     Jalex       啪啪啪
                                     fancy0305   重訓一姊
                                     fancy0305   重訓一姊
SELECT DISTINCT `username`
FROM user1                 username
                             ensky
                             Jalex
                             fancy0305
Select                        score
                                     username    score
SELECT SUM(`score`)   SUM(`score`)   ensky       75
                                     Jalex       85
FROM `score`          350
                                     hwchiu      90
                                     crack1108   90
                                     smartboy    10
SELECT SUM(`score`) AS `sum`
                       sum
FROM `score`
                        350


SELECT MAX(`score`) AS `max`         max
FROM `score`                         90
Select Count                  user1
                                    username    nickname

SELECT COUNT(*)      COUNT(*)
                                    ensky       小天
                                    Jalex       啪啪啪
FROM `user1`         5
                                    Jalex       啪啪啪
                                    fancy0305   重訓一姊
                                    fancy0305
SELECT COUNT(*) AS `count`
                                                重訓一姊

                      count
FROM `user1`
                         5


SELECT COUNT(DISTINCT username) AS `count`
FROM ` user1 `
                                max
                                3
Select subQuery          score
                               username    score
SELECT *                       ensky       75
                               Jalex       85
FROM `score`                   hwchiu      90

WHERE score = (                crack1108   90
                               smartboy    10
  SELECT MAX(`score`)
  FROM `score`
)    username score
     hwchiu      90
     crack1108   90
Update              score
                                username    score
UPDATE `score`                  enskyy      75
SET username = "ensky"          Jalex       5
WHERE username = "enskyy"       hwchiu      90
                                crack1108   90
UPDATE `score`                  smartboy    10

SET `score` = 85
WHERE username = "Jalex"

UPDATE `score`
SET `score` = `score` + 10
Delete
DELETE FROM `user`
WHERE nickname = "啪啪啪"


                  User
     id   username    nickname
     1    ensky       小天
     2    Jalex       啪啪啪
     3    fancy0305   重訓一姊
Not Only SQL
關聯式資料好用歸好用,也不一定適合所有
case,他也有一些缺點,如:

•   速度很慢
•   擴展性不夠好
•   容錯率不夠高
•   要先定義欄位,對彈性的使用上不便
Not Only SQL
而這些缺點在百TB、甚至PB為單位的資料量
處理的時候就會浮現出來。

比方說google會將使用者「搜尋紀錄」以及
「最終連過去哪裡」存起來,這資料量是非
常龐大的,無法以傳統Database做儲存及操作。
Not Only SQL
也因此有很多「非關連式」的Database興起,
其中分為以下種類:
• 文件式資料庫:
  – MongoDB, SimpleDB
• Key-Value儲存
  – 最終一致性 – Cassandra
  – 硬碟 – BigTable, HBase
  – Ram – Redis, Memcached
Homework
• http://vm2.ensky.tw/phpMyAdmin
1. 在test database裡面的user table裡
   新增自己的資料(用介面)
2. 用SQL把自己的資料刪掉
3. 用INSERT新增自己的資料
   用UPDATE把自己的user.id改成user.id – 1
4. 用INSERT把interest, user_interest的資料新增完
5. 用SELECT + JOIN一次把三個table的資料讀出來

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

OpenWebSchool - 05 - MySQL