mysql 投影,MySQL —— select

select语句使用详解

select语句是基础操作中比较复杂的部分,我们单拿出来详细解析一下。还是以上一篇文章里的student表为例。

select * from student:查询student表中所有记录。

create table stu2 select * from student:创建一个stu2表,内容与student是一样的,但注意,主键值是不一样的。

因此我们就可以使用alter table stu2 modify id int not null auto_increment primary key这个SQL语句来重新定义主键'id'。

投影和选择:

投影:select name,age from stu2。选择某几列作为查询内容,这叫做投影。

select name as 姓名,age as 年龄 from stu2:对列投影进行重命名。

选择:select * from stu2 where id>3。选择某几行作为查询内容,这叫做选择。

DISTINCT:去掉重复行。

select DISTINCT name,age,sex from stu2:去掉重复的name,age,sex段数据。

条件。select * from stu2 where name='张三' and id>3:where的选择。and表示与,也可以用or表示或。

select * from stu2 where id in(3,5,6):表明显示id为3,5,6的三行数据。

select * from stu2 where id in(select id from stu2 where sex = 'M':子查询。子查询中表示表中id所有为性别为M的id显示出来并作为条件。那么外层表示使用这些id显示在表上(当然此句只是为了嵌套,并不需要写的这么麻烦)。

select * from stu2 where sex is null or birth is null:判断为空时必须使用is,而不是'='。

select * from stu2 where id between 2 and 5:数据条件在2和5之间。

假设现在数据库dep和emp中的数据如下所示:(emp中dep_id为dep外键)

8aed255d4a43

image.png

select count() from dep:统计dep表总共有多少行。

此时注意:如果count(列名),那么返回的行数是不包含对行中参数有NULL的统计的。

select max(age) from emp:统计emp表中age最大的行。

select avg(age) from emp:统计平均值。

select dep_id,count(dep_id) from emp group by dep_id:group by的作用:看上图,我们对dep_id这一列的元素进行分组,即dep_id为1,2,3三个数进行分组,求出每一个dep_id总共占几行,select后面的dep_id表示我现在要显示的是哪一列。如果没有group by,那么我们不能按dep_id的数字不同来分别求行数。

8aed255d4a43

image.png

select dep_id,count(dep_id) from emp group by dep_id WITH ROLLUP:对结果再汇总。

8aed255d4a43

image.png

select dep_id,count(dep_id) from emp group by dep_id having count(dep_id)>1:having相当于条件过滤,相当于where,但注意,在group by后面我们不能用where,只能用having。

select * from emp order by age asc(desc):按年龄(age)升序(降序)排列。

8aed255d4a43

image.png

select * from emp order by sex asc,dep_id asc:先根据第一个条件升序排列,再根据第二个条件升序排列。

select * from emp limit 3:只想要三行数据。

select * from emp limit 2,3:分页查询。从第3条数据开始。

select e.id,d.name as dname,e.name as ename,e.age,e.sex from dep d,emp e where d.id=e.dep_id;

8aed255d4a43

image.png

语句释义:from后面的dep和emp都被重命名为d和e,然后select的列有e.id,dname,ename,e.age,e.sex。条件过滤为d.id=e.dep_id。

上面的SQL语句被称为多表查询。

那么现在我们在dep中插入一个NULL值的数据。

insert into dep values(null,'人力资源')。

LEFT JOIN与RIGHT JOIN语句(外联查询)

1.LEFT JOIN,左外连接,以左表为基准,到右表找匹配的数据,找不到匹配的用NULL补齐,显示左表的全部记录及右表符合连接条件的记录。

select * from t1 left join t2 on t1.id=t2.id;

2.RIGHT JOIN,右外连接,与左外连接呈对称形式。

注意:如果我们此时select *,那么若t1和t2两个表中字段不同,则会将所有字段显示出来,但基准依旧是某一个表,如t1里id为1和2,t2里id为1和3,那么上面左外联语句就会显示所有id为1和2的结果,而不会显示t2中id为3的结果。

INNER JOIN语句(内联查询)

内联查询:只显示符合连接条件的记录。

select * from t1 inner join t2 on t1.id=t2.id;

这条SQL语句意为:搜索所有列,找出符合t1.id=t2.id条件的记录,匹配的显示不匹配的不现实(即不会用NULL补齐)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值