mysql学习笔记(三)
上一节学习了使用cmd在mysql环境下进行基本的数据库和表单操作,本节将学习更进一步的操作:多表单组合查询、多表单匹配查询、指定查询格式。
1、多表单组合查询(获取不同表单的相同字段内容)
如两个表单分别如下图:
- 返回不重复数据:union
select colume1 from table_name1 union select colume2 from table_name2;
- 返回所有数据,含重复:union all
select colume1 from table_name1 union all select colume2 from table_name2;
- 按条件组合查询:
select country,web_name from web_sites where country='cn' union select country,app_name from app_sites where country='cn' order by country;
2、多表单匹配查询(获取多表单不同字段内容)
在两个以上表单中查询数据:
- inner join(内连接):同时查询多个表单,获取两个表单中互相匹配关系的记录。
- left join(左连接):同时查询多个表单,获取左表单中的记录,即使右表中没有相应记录。
- right join(右连接):同时查询多个表单,获取右表单中的记录,即使左表中没有相应记录。
如图两个表单,
3、指定查询格式
- 查询后按任意指定顺序排列:order by
select *from table_name order by column_name asc;(asc升序,desc降序)
- 对查询结果进行分组展示:group by
select column_name,function(column_name) from table_name group by column_name;
这里的function可以是count,sum,avg等等,group by后面接按什么字段名分组。
如对一个新表单:
查询后结果按姓名排序。
- 在分组基础上再执行相应函数操作:
select column_name,function(column_name) from table_name group by column_name with rollup;
如图表示,按名字分组,分别统计每个人的总共登陆次数。其中NULL表示以上所有次数相加的总数。
- 使用coalesce函数来替换掉null值:select coalesce(a,b,c);
参数说明:如果a==null,则选择b;如果b==null,则选择c;如果a!=null,则选择a;如果a b c 都为null ,则返回为null(没意义)。