Database and SQL (2)- SELECT进阶

博客介绍了SQL查询中的几个重要内容。包括用String patterns处理模糊查找,如查找名字以R开头的数据;Range可选择特定范围的数据,如页数在290到300之间的书;Sets能让代码更简便。还介绍了用‘order by’排序,‘DISTINCT’消除重复行,以及‘group by’和‘having’的联用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 联用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值