您的位置:首页 > 数据库 > MySQL

mysql学习笔记(6)

2015-11-09 15:29 621 查看
一、几个常用的函数

1. concat()  连接函数,字符串连接

select concat(id,'-',age) from user;

# 显示表头,concat(id,'-',age)

# 显示数据,1-18

select concat('aa','bb',cc');

# 显示表头,concat('aa','bb',cc')

# 显示数据,aabbcc

2.rand()   随机数,随机

select * from user order by rand() limit 3;  # 随机取3行数据

3.统计函数

count()  # 统计个数

sum()   # 求和

max()  # 最大数

min()  # 最小数

avg()  # 平均数

select count(id) / sum(money) / avg(age) / max(age) / min(age) from user;

# 查询id个数 / 钱总和 / 平均年龄 / 最大年龄 / 最小年龄

# 查询时尽量使用主键索引加快搜索速度

eg:select count(id) from user where name='user4';

# 查询有多少个名字为user4的数据

二、group by (分组聚合的使用)

# 只分组没有意义,必须使用函数去聚合

select name,count(id) from user group by name;

# 目的:查询各name出现的次数

# 将user表中的数据按照name来分组,然后统计每个name出现的次数

select name,count(id) from user group by name order by count(id);

# 演示分组聚合后再排序

# group by 必须放在order by 之前

select name,count(id)top from user group by name having top>=2 order by top desc;

#  having后面接筛选条件,这里不能用where,group by 必须放在having之前

三、多表查询

1.普通多表查询  

2.左/右链接查询

3.嵌套查询

4.使用优先级:1>2>3

1.普通多表查询

# 两个表之间必须有个关联字段

select * from user,post where user.id=post.uid;    #  筛选出user表id和post表uid相同的数据

eg:

# 有表user(id,name,age)和post(id,uid,title,content),进行论坛用户和帖子统计

# 统计谁发了什么帖子

select user.name, post.title from user,post where user.id=post.uid;

# 统计发了帖子的人的发帖数

select user.name, count(user.id) from user,post where user.id=post.uid group by user.id;   # 在此处user.id==post,uid==user.name,但user.id是主键索引

2.左/右链接查询

# 其中一个表全部显示,另一个表只显示与其有关系的数据(左右指的是全部显示的表放在左边还是右边)

# 演示左链接 (user.name 显示在左边且全部显示)

# 统计所有用户的发帖情况(未发帖的用户,post.title 显示为null)

select user.name,post.title from user left join post on user.id=post.uid;

# 统计所有用户的发帖数量(未发帖的用户,count(post.title) 显示为0)

select user.name,count(post.title) from user left join post on user.id=post.uid group by user.id;

3.嵌套查询

需要查询所有发过贴的用户时,用 “select user.name from user,post where user.id=post.uid;"查出来的会有重复项,这时候应该:

select distinct user.name from user,post where user.id=post.uid;   # 普通查询

select name from user where id in(select uid from post);   # 嵌套查询

# 嵌套查询有局限性,只可以用于单表数据查询,不可以一次性显示多个表的内容,只不过是单表中的其中一个条件与另一个表发生了关联

# 但是嵌套查询语句很好理解

# 嵌套查询优化不好,如果子表语句里用到了where条件语句,母表中的索引将会失效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: