第四章——检索数据
1)检索单个列:
select list from table1;
2)检索多个列:
select list1,list2 from table1;
3)检索所有列:
select * from table1;
4)对结果去重:
select distinct col from table1;
使用distinct关键字对结果去重
5)限制结果:
select col from table1 limit 5;
限制结果返回的行数
select col from table1 limit 3,3;
从第四行开始返回,一共返回三行数据。
可以将第一个理解为偏移量
6)使用限定的名称
select table1.col from table1;
和C语言的结构体的使用差不多,表名.列名 来限定查找的表,在多个表中存在相同的字段尤为重要
select col from db.table1
也可以使用 数据库名称.表格名 来对表格的查找进行限定。
第五章——排序检索数据
1 )按照某一个列进行排序
select col
from table1
order by id;
2)按照多个列进行排序
select FirstName ,LastName
from person
order by FirstName,LastName;
先按照第一种排序方案排序,在按照第一种排序方式相同的前提下,按照第二种排序方式排序。
3)指定排序方向,默认为升序asc
select col
from table1
order by id desc;
使用desc关键字来指明降序排序。
如果依据多个列来排序则要分别每个列来指定排序规则
select FirstName ,LastName
from person
order by FirstName desc,LastName;
4)限定排序+limit可以找到最大值和最小值
select col
from table1
order by id desc
limit 1;
第六章——过滤数据
1)使用where子句查询
select FirstName, LastName
from person
where FirstName = 'pat';
在表中筛选出符合where子句当中的filter condition的数据。
- where子句的操作符
- where子句单个值匹配
- where子句使用between关键字
select col
from table1
where value between 20 and 30;
使用between关键字的时候需要用and来连接两个值来限定范围。
2)空值检查
空值检查不使用前面的操作符。
select product_name
from goods
where product_price IS null;
第七章——数据过滤
1)组合where子句查询
- AND操作符
select product_name
from goods
where product_price = 100 and product_num = 100;
使用and连接多个过滤条件,每多加一个条件就要多使用一次and,最终的查询结果满足所有的过滤条件
- OR操作符
select product_name
from goods
where product_price = 100 or product_num = 100;
使用or连接多个过滤条件,每多加一个条件就要多使用一次or,最终的查询结果满足至少一个过滤条件。
- 计算次序
select product_name
from goods
where product_price = 100 or product_num = 100 and product_color = 'white';
SQL(像多数语言一样)在处理OR操作符前,优先处理AND操作符。上面的语句中,后两个条件被视作一个整体,得到的结果中会含有不是白色的产品。
如果要保证最终的结果当中含有白色的产品,需要使用圆括号提高前面两个条件的优先级。
select product_name
from goods
where (product_price = 100 or product_num = 100) and product_color = 'white';
2)IN操作符
IN操作符用于指定条件范围
select student
from StudentInfo
where studentID IN (200,300);
IN后面的圆括号囊括了所有的可能条件。
3)NOT操作符
Not操作符实现在去除符合其后面条件的数据。对于正难则反的情况十分好用。
select student
from StudentInfo
where studentID NOT IN (200,300);