簡單的sql操作

學習資料來自於https://www.codecademy.com/,所有的sql語句以SQLite關係型數據庫管理系統爲例。

Unit 1. Manipulation

示例表:

1.1創建表

示例: create table celebs(id integer, name text, age integer);//括號中列出各字段以及各字段的類型

1.2 插入記錄

示例: insert into celebs(id, name, age) values(1, 'Justin Bieber', 21 );//第一個括號的字段順序不一定,但是隻要values後面的字段與前面的字段順序對應就行了

1.3 修改/更新記錄

示例: update celebs set age=22 where id = 1;

1.4 修改/更新表結構

示例: alter table celebs add column twitter_handle text;//當添加了新的列時,以前已經存在的數據的這一列自動設置爲NULL值

1.5 刪除

示例: delete from celebs where twitter_handle is null;

Unit 2. Queries

示例表:


2.1 distinct的使用

說明:過濾掉結果集中的重複值。SELECT DISTINCT is used toreturn unique values in the result set. It filters out all duplicate values.

示例: select distinct genre from movies;

2.2 where子句可用的關係運算符

說明:關係運算操作產生了一個條件運算,它可以返回True或者False,用於where子句中。 Operators create a condition thatcan be evaluated as either true or false. Common operators used with the WHERE clause are: =, !=, >, <, >=, <=

2.3 like的使用

說明:1.like用於where子句中,用於查找某一列的特定的模式。

            2.like後面的模式串中可以使用通配符。可以使用下滑線_和%。

示例:  select * from movies where name like 'Se_en';

返回結果:


說明:Se_en中的_表示通配符,可以使用任何單個字符替代它,而%可代表0個或多個字符。


示例:select * from movies where name like 'a%';

返回結果:



示例: select * from movies where name like '%man%';

返回結果:


說明:SELECT * FROM movies WHERE name LIKE 'A%';
% is a wildcard character(通配符) that matches zero or more missing letters in the pattern.%代表0個或多個字符。
A% matches all movies with names that begin with "A"
%a matches all movies that end with "a"
SELECT * FROM movies WHERE name LIKE '%man%';
You can use % both before and after a pattern. Here, any movie that contains the word "man" in its name will be returned in the result set. Notice, that LIKE is not case sensitive. "Batman" and "Man Of Steel" both appear in the result set. like對大小寫不敏感。

2.4 between and的使用

示例: select * from movies where name between 'A' and 'J';

             select * from movies where year between 1990 and 2000;

2.5 AND 與OR運算

說明:AND and OR operator can be used with the WHERE clause,大小寫皆可。

2.6 排序order by

示例: select * from movies order by imdb_rating desc;

說明:按某列進行排序,排序可依據與字母序和數值大小順序;desc是降序,asc是升序,DESC is a keyword in SQL that is used with ORDER BY to sort the results in descending order (high to low or Z-A). Here, it sorts all of the movies from highest to lowest by their IMDb rating.It is also possible to sort the results in ascending order. ASC is a keyword in SQL that is used with ORDER BY to sort the results in ascending order (low to high or A-Z).

2.7 limit的使用

 要求:write a query that only returns the three lowest rated movies.

 示例: select * from movies order by imdb_rating asc limit 3;

 說明:Sometimes even filtered results can return thousands of rows in large databases. In these situations it becomes important to cap the number of rows in a result set.
LIMIT is a clause that lets you specify the maximum number of rows the result set will have. Here, we specify that the result set can not have more than three rows.

Unit 3. Aggregate Functions

示例表:


3.1 count()的使用

要求:count how many apps are in the database

示例:select count(*) from fake_apps;

說明:用於計算行數。一般用列名作爲參數,計算參數列的列值不爲NULL的行數,如果不是依據於某列而是每一行,則使用*作爲參數。The fastest way to calculate the number of rows in a table is to use the COUNT() function.
COUNT() is a function that takes the name of a column as an argument and counts the number of rows where the column is not NULL. Here, we want to count every row so we pass * as an argument.

3.2 group by的使用

要求:Count the number of apps at each price.

示例: select price, count(*) from fake_apps group by price;

返回結果:


說明:group by僅用於聚合函數,它與select子句協作,把具有相同值得數據分爲一組。Here, our aggregate function is COUNT() and we are passing price as an argument to GROUP BY. SQL will count the total number of apps for each price in the table.  It is usually helpful to SELECT the column you pass as an argument to GROUP BY. Here we select price and COUNT(*). You can see that the result set is organized into two columns making it easy to see the number of apps at each price.

要求:Count the total number of apps at each price that have been downloaded more than 20,000 times.

示例: select price, count(*) from fake_apps where downloads > 20000 group by price;

3.3 sum()的使用

要求:What is the total number of downloads for all of the apps combined?

示例: select sum(downloads) from fake_apps;

要求:Calculate the total number of downloads for each category.

示例:select category, sum(downloads) from fake_apps group by category;

3.4 max()的使用

要求:How many downloads does the most popular app have?

示例: select max(downloads)from fake_apps;

要求:Return the names of the most downloaded apps in each category.

示例: select name, category, max(downloads)from fake_apps group by category;

3.5 min()的使用

要求:What is the least number of times an app has been downloaded?

示例:select min(downloads)from fake_apps;

3.6 avg()的使用

要求:Calculate the average number of downloads for an app in the database.

示例: select avg(downloads)from fake_apps;

要求:Calculate the average number of downloads at each price.

示例: select price, avg(downloads) from fake_apps group by price;

返回結果:


3.7 round()的使用

要求:Make the result set more readable by rounding the average number of downloads to two decimal places for each price.

示例: select price, round(avg(downloads),2) from fake_apps group by price;

返回結果:


說明:round函數以一個列名和一個整數作爲參數,保留整數參數的小數位數,ROUND() is a function that takes a column name and an integer as an argument. It rounds the values in the column to the number of decimal places specified by the integer. Here, we pass the column AVG(downloads) and 2 as arguments. SQL first calculates the average for each price and then rounds the result to two decimal places in the result set.

Unit4. Multiple Tables

    The data in these tables are related to each other. Through SQL, we can write queries that combine data from multiple tables that are related to one another. This is one of the most powerful features of relational databases.

    Imagine a database with two tables, artists and albums. An artist can produce manydifferent albums, and an album is produced by an artist.

示例表:


4.1 主鍵

要求:假設表albums已有,現在創建表artists

示例:create table artists(id integer primary key, name text);

說明:A primary key serves as a unique identifier for each row or record in a given table. The primary key is literally an id value for a record. We're going to use this value to connect artists to the albums they have produced.

By specifying that the id column is the PRIMARY KEY, SQL makes sure that:
(1) None of the values in this column are NULL
(2) Each value in this column is unique

A table can not have more than one PRIMARY KEY column.

4.2 多表查詢

示例:  select albums.name, year,artists.name from albums, artists;

4.3 join的使用

示例:select * from albums join artists on albums.artist_id = artists.id;

4.4 left join的使用

數據庫裏並不是每一個album 都對應一個artist,而4.3的查詢將不會返回那些沒有artist的album,如果也要返回這樣的album,那麼可使用left join

示例:select * from albums left join artists on albums.artist_id= artists.id;

返回結果:


說明:Outer joins also combine rows from two or more tables, but unlike inner joins, they do not require the join condition to be met. Instead, every row in the left table is returned in the result set, and if the join condition is not met, then NULL values are used to fill in the columns from the right table.
            The left table is simply the first table that appears in the statement. Here, the left table is albums. Likewise, the right table is the second table that appears. Here, artists is the right table.

4.5 使用as重命列名

當兩個表有相同的列名時容易產生混淆,可用as解決

示例:select albums.name as 'Album', albums.year, artists.name as 'Artist' from albums join artists on albums.artist_id = artists.id where albums.year > 1980;

說明:AS is a keyword in SQL that allows you to rename a column or table using an alias. The new name can be anything you want as long as you put it inside of single quotes. Here we want to rename the albums.name column as 'Album', and the artists.name column as 'Artist'.
             It is important to note that the columns have not been renamed in either table. The aliases only appear in the result set.

補充

1. having的使用

參考自:http://www.cnblogs.com/wang-123/archive/2012/01/05/2312676.html

示例:

 create TABLE Table1 (
        ID int identity(1,1) primary key NOT NULL,   
        classid int, 
        sex varchar(10),
        age int); 

查詢table表查詢每一個班級中年齡大於20,性別爲男的人數:

select COUNT(*) as '>20歲人數',classid  from Table1 where sex='男' group by classid,age having age>20 ;

說明:
--需要注意說明:當同時含有where子句、group by 子句 、having子句及聚集函數時,執行順序如下:
--執行where子句查找符合條件的數據;
--使用group by 子句對數據進行分組;對group by 子句形成的組運行聚集函數計算每一組的值;最後用having 子句去掉不符合條件的組。
--having 子句中的每一個元素也必須出現在select列表中。有些數據庫例外,如oracle.
--having子句和where子句都可以用來設定限制條件以使查詢結果滿足一定的條件限制。
--having子句限制的是組,而不是行。where子句中不能使用聚集函數,而having子句中可以。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章