1. Distinct用法
1.1 在count计算不重复的记录的时候
select count(distinct(domain)) from url_host;
计算url_host表中domain不同的记录有多少条。
1.2 在需要返回记录不同的id的具体值的时候
select distinct ip from url_host;
返回url_host表中不同的ip的具体的值。
例子:
查询总共有多少个高校有https网站,即为certificate_issuer不为空
select count(distinct domain) from url_host_copy where certificate_issuer!='';
2. ORDER BY用法
2.1 对查询结果按照多个数据列进行排序
select sn, host from url_host order by sn asc, host desc;
查询结果按sn升序排列,然后排序好后的sn所对的host又降序排列。
2.2 order by语句后跟条件表达式
select last_name, first_name, death from president order by if(death is null,0,1), death desc;
IF()函数的作用是对紧随其后的表达式(第一参数,就是null)进行求值,再根据表达式求值结果的真假返回它的第二参数(0)或第三参数(1)。此例 IF 判断为真返回0,假返回1。
例子:
查询具有certificate_issuer网站的高校中每个高校有多少个主机并按domain进行分组
select domain,count(*) from url_host_copy where certificate_issuer!='' group by domain limit 10;
3. LIMIT用法
3.1 从查询结果中的中间部分抽出一部分数据记录
select * from url_host limit 10, 5;
查询url_host表中跳过前十个记录之后的5条记录。
3.2 从数据表中随机抽出一条或多条 数据记录
select * from url_host order by rand() limit 2;
4. CONCAT用法
4.1 将concat中的两个列合二为一,成为一个一空格分隔的字符串
select concat(sn,' ',host) as name from url_host limit 5;
查询的结果是sn和host两列合二为一成为name列。
4.2 输出列的别名里包含空格符,就必须把它放到一组引号中
select concat(sn,' ',host) as 'sn name' from url_host limit 5;
输出列名是sn name。
5. LIKE用法
5.1 模糊查询把以a或A字母(不分大小写)开头的host查找出来
select * from url_host where host like 'a%' limit 5;
5.2 模糊查询将查询包含B或b字母的host列
select * from url_host where host like '%b%' limit 5;
5.3 将查询仅有4个字母构成的host列
select * from url_host where host like '____' limit 5;
'___' 这由四个下划线组成。
6. GROUP BY用法
6.1 一个数据表中 ip 列只有0和1,现在要统计0和1的ip个数
select ip, count(*) from url_host group by ip;
6.2 统计一个数据列中到底有多少种不同的取值
select sn, count(*) as count from url_host group by sn order by count desc limit 10;
6.3 HAVING子句允许COUNT()之类的汇总函数的计算结果出现
select sn, count(*) as count from url_host group by sn having count > 50 order by count desc;
7. 查找字段空,不为空的方法
7.1 不为空
select domain,certificate_issuer from url_host_copy where (domain='shnu.edu.cn' and certificate_issuer!='');
select domain,certificate_issuer from url_host_copy where (domain='shnu.edu.cn' and certificate_issuer<>'');
这两句查找certificate_issuer字段不为空的数据。
7.2 为空
select domain from url_host_copy where isnull(certificate_issuer);
select domain from url_host_copy where certificate_issuer is null;
这两句查找certificate_issuer字段为空的数据。
8. 创建视图
8.1 第一类
create view certificate_view as select * from url_host_copy where certificate_issuer!='';
创建certificate_view视图,选择url_host_copy表中的所有字段,条件是certificate_issuer不为空。
8.2 第二类
create view certificate_view_1 as select sn,domain,certificate_issuer from url_host_copy where certificate_issuer!='';
选择url_host_copy中特定的字段创建视图。
8.3 第三类
create view certificate_view_2(sn,host,domain,certificate) as select sn,host,domain,certificate_issuer from url_host_copy where certificate_issuer!='';
自己定义创建视图中的字段名称,替代默认选择表中的字段名称。