1.union和union all的区别
union:将查询出来的结果去重展示
union all:将查询的所有的结果展示
举个栗子:
employees表:
salaries表:
#union
select employee_id from Employees union select employee_id from Salaries;
查询结果:
#union all
select employee_id from Employees union all select employee_id from Salaries;
2.group_concat() 函数
group_concat() 函数:将group by之后的字段数据以逗号拼接起来
举个栗子:
activities表:
select sell_date,group_concat(product) from activities group by sell_date;
查询结果:
3.having子句用法
having子句一般用于分组(group by)之后进行数据的筛选,可以包含聚合函数。
执行顺序:where→group by→having→order by
举个栗子:
person表:
#找出重复的邮箱
select email from person group by email having count(1) > 1;
查询结果:
4.case when多个条件用法
用法一:case 字段
when 条件 then 结果
when 条件 then 结果
else 结果 end
用法二:case
when 表达式 then 结果
when 表达式 then 结果
else 结果 end
举个栗子:
pig表:
用法一:
select id,name,
case sex
when 0 then '雄'
when 1 then '雌'
else '不详' end as 'sex'
from pig;
查询结果:
用法二:
select id,name,
case
when age > 0 and age < 3 then '小猪'
when age > 3 and age < 6 then '大猪'
else '老猪' end as age
from pig;
查询结果:
如有不对之处 敬请指正