SQL 学习笔记

SQL 学习

废话篇

想写博客很久了,最近终于可以静下心来,也算是好好梳理梳理之前断断续续想了解的知识,也让自己以后便于查询和深入学习
关于SQL,推荐几个可以系统学习SQL的网站

第一个:https://www.codecademy.com/learn/learn-sql(这个网站我觉得还是蛮不错的,先让你跟着写SQL的语句,然后接下来给你解释,我做的学习笔记也是根据这个网站的进度来记的,当然这个好像还得注册账号,我是用Google账号的,然后翻墙)
第二个:http://www.w3school.com.cn/sql/sql_intro.asp(这个是直接文字版的,内容分的比较细致,可以在学习SQL的时候好好看看)
第三个:https://www.sqlteaching.com/(感觉跟第一个很类似,支持实时在网页上操作数据库)
最后:https://www.zhihu.com/question/19552975(这个是知乎上关于如何学习SQL的一些大神们的回答)
新加入一个sql的查询址:http://www.w3school.com.cn/sql/sql_syntax.asp

学习篇

ps:关于这个笔记,没有从一开始就记录,所以在学习了第二个课程的时候,才突然觉得需要记录一下,也就有了下面的这些内容.学而不思则罔,思而不学则殆.我深知这些道理,却一直只想着工作和学习,耽于做笔记,希望以后不会再这样.这里面有自己的理解,也有网站自己给的解释,我摘抄了一些,如果有哪里不对,欢迎指正.

课时一

SELECT * FROM movies WHERE name LIKE '%man%';//查询name列中包含man的name,不区分大小写
SELECT * FROM movies WHERE name BETWEEN 'A' AND 'J';//检索首字母从A到J的电影,包含A不包含J
SELECT * FROM movies WHERE year BETWEEN 1990 AND 2000;//生产年份由1990到2000的电影,包含1990,包含2000
SELECT * FROM movies WHERE year BETWEEN 1990 AND 2000 AND genre = 'comedy';//在1990到2000年的电影里检索genre是comedy的电影
 AND is an operator that combines two conditions. 
SELECT * FROM movies WHERE genre = 'comedy' OR year > 1980;
The OR operator evaluates each condition separately and if any of the conditions are true then the row is added to the result set.
SELECT * FROM movies ORDER BY imdb_rating DESC;//将movies表中的imdb_rating列的数据按照从大到小的顺序依次排列下来
ORDER BY is a clause that indicates you want to sort the result set by a particular column either alphabetically or numerically.
SELECT * FROM movies ORDER BY imdb_rating ASC LIMIT 3;//找到imdb_rating列分数最低的三部电影,按照从小到大的顺序一次排列
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.

总结:

SELECT is the clause you use every time you want to query information from a database.
WHERE is a popular command that lets you filter the results of the query based on conditions that you specify.
LIKE and BETWEEN are special operators that can be used in a WHERE clause
AND and OR are special operators that you can use with WHERE to filter the query on two or more conditions.
ORDER BY lets you sort the results of the query in either ascending or descending order.
LIMIT lets you specify the maximum number of rows that the query will return. This is especially important in large tables that have thousands or even millions of rows.

课时二

In this lesson we are going to learn how to perform calculations using SQL.

SELECT * FROM fake_apps;//查的有id name    category    downloads   price这几列
SELECT COUNT(*) FROM fake_apps;//查的这个数据表的app总数
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.
SELECT COUNT(*) FROM fake_apps WHERE price = 0;//查出在所有的app中的price=0的数目
SELECT price,COUNT (*) FROM fake_apps GROUP BY price;//将不同price分组,统计每组的price的数量
GROUP BY is a clause in SQL that is only used with aggregate functions. It is used in collaboration with the SELECT statement to arrange identical data into groups.
SELECT price,COUNT(*) FROM fake_apps WHERE downloads > 20000 GROUP BY price;//统计不同的price下downloads > 20000的app数量
SELECT SUM(downloads) FROM fake_apps;//统计这张表中所有的下载量
SUM() is a function that takes the name of a column as an argument and returns the sum of all the values in that column. Here, it adds all the values in the downloads column.
SELECT category,SUM(downloads) FROM fake_apps GROUP BY category;//依据app的类别来统计每个类别下的downloads的总和
SELECT MAX(downloads) FROM fake_apps;//获得在这张表中downloads列下的最大数
MAX() is a function that takes the name of a column as an argument and returns the largest value in that column. Here, we pass downloads as an argument so it will return the largest value in the downloads column.
SELECT name,category,MAX(downloads) FROM fake_apps GROUP BY category;//展示category列下的downloads最大的name,其中category是按照A-Z的自然顺序排列的(三列多行的表格来展示筛选出来的数据)
SELECT MIN(downloads) FROM fake_apps;//获得表中downloads列中的最小数
MIN() is a function that takes the name of a column as an argument and returns the smallest value in that column. Here, we pass downloads as an argument so it will return the smallest value in the downloads column.
SELECT name,category,MIN(downloads) FROM fake_apps GROUP BY category;//同上面的MAX类似,不过这次是求最小的
SELECT AVG(downloads) FROM fake_apps;//求出表中所有app的平均downloads
The AVG() function works by taking a column name as an argument and returns the average value for that column.
SELECT price,AVG(downloads) FROM fake_apps GROUP BY price;//将price分组,然后求出每组内的downloads的平均值,这个平均值默认保留到小数点后十位
SELECT price,ROUND(AVG(downloads),2) FROM fake_apps GROUP BY price;//将price分组后,算出每组price内的downloads的平均值,这个平均值保留到小数点后两位
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.
SELECT price,ROUND(AVG(downloads)) FROM fake_apps GROUP BY price;//将price分组后,算出每组price内的downloads的平均值,这个平均值保留成整数,整数后默认添加.0

总结:

    Aggregate functions combine multiple rows together to form a single value of more meaningful information.
    COUNT takes the name of a column(s) as an argument and counts the number of rows where the value(s) is not NULL.
    GROUP BY is a clause used with aggregate functions to combine data from one or more columns.
    SUM() takes the column name as an argument and returns the sum of all the values in that column.
    MAX() takes the column name as an argument and returns the largest value in that column.
    MIN() takes the column name as an argument and returns the smallest value in that column.
    AVG() takes a column name as an argument and returns the average value for that column.
    ROUND() takes two arguments, a column name and the number of decimal places to round the values in that column.

课时三

Learn how to query multiple tables using joins.

So far we have learned how to build tables, write queries, and perform calculations using one table. In this lesson we will learn to query multiple tables that have relationships with each other.

Most of the time, data is distributed across multiple tables in the database. Imagine a database with two tables, artists and albums. An artist can produce many different albums, and an album is produced by an artist.

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.
CREATE TABLE artists(id INTEGER PRIMARY KEY, name TEXT);//创建artists,里面包括自增长id和name这两列
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:

None of the values in this column are NULL Each value in this column is unique A table can not have more than one PRIMARY KEY column.
SELECT * FROM albums;//albums这张表的列都有: id  name  artist_id  year
SELECT * FROM artists;//artists这张表的列都有: id  name
SELECT * FROM artists WHERE id = 3;//查找artists表中id = 3的数据内容
SELECT * FROM albums WHERE artist_id = 3;//查找albums 中artist_id = 3的数据内容
//怎么将两张表联系起来,这里给了很好的解释
A foreign key is a column that contains the primary key of another table in the database. We use foreign keys and primary keys to connect rows in two different tables. One table's foreign key holds the value of another table's primary key. Unlike primary keys, foreign keys do not need to be unique and can be NULL.

Here, artist_id is a foreign key in the albums table. We can see that Michael Jackson has an id of 3 in the artists table. All of the albums by Michael Jackson also have a 3 in the artist_id column in the albums table.

This is how SQL is linking data between the two tables. The relationship between the artists table and the albums table is the id value of the artists.
SELECT albums.name,albums.year,artists.name FROM albums,artists;//查找出albums.name,albums.year,对应的artists.name,前者是在albums的表中,后者是在artists的表中

¥¥¥¥¥¥¥¥我是可爱的分割线¥¥¥¥¥¥¥¥

因为还有点别的事情,暂时先写到这里,明天继续,加油
回来了,继续学习啦

//下面这三段就是关于上面那句查询语句的解释
One way to query multiple tables is to write a SELECT statement with multiple table names separated by a comma. This is also known as a cross join. Here, albums and artists are the different tables we are querying.

When querying more than one table, column names need to be specified by table_name.column_name. Here, the result set includes the name and year columns from the albums table and the name column from the artists table.

Unfortunately the result of this cross join is not very useful. It combines every row of the artists table with every row of the albums table. It would be more useful to only combine the rows where the album was created by the artist.
SELECT * FROM albums JOIN artists ON albums.artist_id = artists.id;//在album和artists表中筛选出albums.artist_id跟artists.id相等时候的对应的数据内容
FROM albums specifies the first table we are querying.

JOIN artists ON specifies the type of join we are going to use as well as the name of the second table.Here, we want to do an inner join and the second table we want to query is artists.

albums.artist_id = artists.id is the join condition that describes how the two tables are related to each other. Here, SQL uses the foreign key column artist_id in the albums table to match it with exactly one row in the artists table with the same value in the id column. We know it will only match one row in the artists table because id is the PRIMARY KEY of artists.
SELECT * FROM albums LEFT JOIN artists ON albums.artist_id = artists.id;//这行代码较上面的那行代码只是在JOIN前面多了一个LEFT,但是我观察了这两个查询之后的表内的数据,发现此次显示的表格数据好像只是把那些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.
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;//将albums.name的name列重命名为Album,artists.name的name列重命名为Artist,然后挑出在albums表和artists表中的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.

总结

Primary Key is a column that serves a unique identifier for row in the table. Values in this column must be unique and cannot be NULL.
Foreign Key is a column that contains the primary key to another table in the database. It is used to identify a particular row in the referenced table.
Joins are used in SQL to combine data from multiple tables.
INNER JOIN will combine rows from different tables if the join condition is true.
LEFT OUTER JOIN will return every row in the left table, and if the join condition is not met,NULL values are used to fill in the columns from the right table.
AS is a keyword in SQL that allows you to rename a column or table in the result set using an alias.

画外音:到此为止,一些基本的SQL语句算是学完了,其他的在实战中可能用到的,以后再慢慢细看学习,如果里面有什么错误,欢迎指正,不胜感激

猜你喜欢

转载自blog.csdn.net/liuwanyouyue/article/details/51152671
今日推荐