# SQLite 範例資料庫 下載 ## 下載範例資料庫 https://www.sqlitetutorial.net/sqlite-sample-database/ ![](https://i.imgur.com/86hCk3g.png) ## 解壓縮下載 ![](https://i.imgur.com/iaz7Wov.png) # SQLite GUI Tool 下載 ## 下載SQLite工具 https://github.com/pawelsalawa/sqlitestudio/releases ![](https://i.imgur.com/koul5BU.png) ## 解壓縮下載 ![](https://i.imgur.com/dKaGqHY.png) ## 執行GUI Tool ![](https://i.imgur.com/UxAWpL3.png) ## 開啟選單[DataBase]並選取[Add a DataBase] ![](https://i.imgur.com/9TizlqH.png) ## 選取[資料夾圖示]加入先前下載[範例資料庫] ![](https://i.imgur.com/sdzamZ9.png) ## 選取[OK]完成資料庫加入 ![](https://i.imgur.com/AYgRyRB.png) ## [資料庫]展開,可以看到有[Columns]、[Indexs]、[Triggers],展開[Columns]檢視該[表格]內所有欄位 ![](https://i.imgur.com/81qGxiy.png) ## 完成載入[資料庫]畫面如下,滑鼠點兩下可檢視資料庫內所有[表格](Table) ![](https://i.imgur.com/Qo5gORv.png) ## 試著對表格[albums]點選滑鼠右鍵,選擇[Generate query for table]>>[SELECT] ![](https://i.imgur.com/pR64Px7.png) ## GUI Tool會自動產生 select 語法 ![](https://i.imgur.com/Ek7Y95U.png) ## 點選[▶]執行SQL語法,下方會回傳[執行結果] ![](https://i.imgur.com/BHnQzJE.png) # 開始使用SQL語法 ## 範例資料庫結構 ![](https://i.imgur.com/CTnHWk5.png) ## 使用 Select (1) #### 使用*,取出客戶檔中所有資料 ---> ```sql= SELECT * FROM customers ``` #### 使用Top,取出客戶檔中前N筆資料 ---> ```sql= SELECT * FROM customers limit 10 ``` #### 使用Count,計算客戶檔有幾筆資料 ---> ```sql= SELECT count(*) as cust_count FROM customers ``` #### 使用查詢條件,找到居住在米國的客戶 ---> ```sql= SELECT * FROM customers WHERE Country='USA' ``` #### 使用模糊查詢條件%,找出使用Gmail的客戶 ---> ```sql= SELECT * FROM customers WHERE Email like '%@gmail.com' ``` #### ==*練習題: 公司計劃對居住在 加州(CA)或紐約(NY) 地區的客戶,進行拜訪~要你提供客戶資料(輸出格式: Name(FirstName+LastName)、Address、Phone)*== ```sql= SELECT FirstName||' '||LastName,Address,Phone FROM customers where State='CA' or State='NY' ``` ` ## 使用 Select (2) #### 使用Distinct,分析客戶來自哪幾種國家 ---> ```sql= SELECT Distinct Country FROM customers ``` #### 使用Order by,分析客戶來自哪幾種國家並依照國家名稱A-Z排序 ---> ```sql= SELECT Distinct Country FROM customers order by Country ``` #### 分析客戶資料中,各個國家的客戶數量分佈 ---> ```sql= SELECT Country,count(*) FROM customers group by Country ``` #### ==*練習題: 請找出客戶數量最多的三個國家 輸出格式:(國家、客戶數量)*== ## 使用 join ![](https://i.imgur.com/Qy3jucp.png) #### 使用join,查出客戶消費總金額 ---> ```sql= SELECT a.CustomerId,FirstName,LastName,sum(Total) FROM customers a join invoices b on a.CustomerId=b.CustomerId group by a.CustomerId,FirstName,LastName ``` #### 試著刪除一個客戶的消費記錄 ---> ```sql= delete from invoice_items where InvoiceId in (1,12,67,196,219,241,293) delete from invoices where InvoiceId in (1,12,67,196,219,241,293) ``` #### 使用 left join ,查出客戶消費總金額 ---> ```sql= SELECT a.CustomerId,FirstName,LastName,sum(Total) FROM customers a left join invoices b on a.CustomerId=b.CustomerId group by a.CustomerId,FirstName,LastName ``` #### ==*練習題: 請找出最暢銷的專輯名稱(專輯內單曲被購買最多次)*輸出格式:(專輯名稱、購買次數)==