String patterns, Range, Sets
1. String patterns。
如果我们需要选择一个叫author的数据里的某个人,但是我们只记得他名字是以R开头的,这种情况怎么办?
String patterns就是用来处理这种情况的,灵活应用即可很方便的查找。
SELECT firstname from author
where firstname like 'R%';
% 叫做wildcard character,可以放在字符前中后,用来substitute 其他字符。
LIKE predicate 用来处理我们上面说的这种情况。
2.Range
如果我们想要选择一个叫book的数据库中,页数在290到300之间的书
SELECT title, pages from book
where pages between 290 and 300;
3. Sets
比较下面两种效果一样的写法,哪种更加简便?第二行的代码就是使用了Sets,使得代码写的更加简便。
select firstname, lastname, country from author
where country='AU' or country='BR';
select firstname, lastname, country from author
where country in ('AU','BR');
Sorting Result Set
使用‘order by’ clause, 如
select title from book
order by title;
order by 默认排序是递增的,如果需要递减,则需要增加 desc, 如
select title from book
order by title desc;
在选择多个列时,也可以使用column number来决定使用哪个列来作为排序依据,如需要按照pages的递增来排列:
select title, pages from book
order by 2;
Grouping Result Set
选择时消除属性重复的row,需使用DISTINCT clause,如以下代码,将获取country列表,每个country只显示一次
select distinct(country) from author;
如果我们需要知道有多少author分别来自这些country,第一行的代码将会返回两个列,第二列自动获取一个列名:2,如果需要定制列名,需要使用第二行的代码将列名设为 count:
select country, count(country) from author
group by country;
select country, count(country) as count from author
group by country;
我们可以使用having来设置group by的条件:
select country, count(country) as count
from author group by country having count(country) > 4;
这样只会返回country出现次数大于4的行。注意:having只能和group by 联用。