数据库查询

单表查询

说明:语法:select 字段名称,字段名称2 from 表名 条件

1.查询所有记录

select * from t3;

2.只查询指定字段

select 字段名1,字段名2 from t3;

3.where单条件查询

select id,name,salary from t3 where id>5;

4.去重查询 (distinct)

select distinct name,salary from t3;

注意:只能查询某一个字段查询多个不生效

5.运算查询

select name,salary*12 as 年薪 from t3;

“as” 给字段做别名可以和四则运算一起用

6.多条件查询

and :多个条件同时满足

select id,name from t3 where id>=3 and id<=5;

or:满足一个即可

select id,name from t3 where id<3 or id>7;

between A and B:在AB之间

select id,name from t3 where id between 5 and 7;

7.关键字 is null 或者 is not null

select name,job_description from t3 where job_description is null;

8.关键字IN集合查询

select id,name from t3 where id in (1,3,5);

9.排序查询 DESC 、ASC 、 order by

order by 字段名:以哪个字段进行排序

desc:降序

asc: 升序

select id,name,salary from t3 order by salary desc;

10.限制查询的记录数 limit

对结果集限制:只输入指定数量的记录

select id,name,salary from t3 order by salary desc limit 5;

limit n,m:从第n条记录下面截取m条记录

11.集合函数

count():计数统计

select count(*) from 表名; #统计表中有多少条记录

#统计满足条件的记录有多少条

select count(*) from t3 where salary="2200";

max():最大值

select max(salary) from t3;

min():最小值

select min(salary) from t3;

avg():平均值

select avg(salary) from t3;

sum():求和

select sum(salary) from t3;

12.模糊查询(通配符)

使用like 关键字

_ 任意单个字符 (不包括零个字符)

% 所有字符,注意与*的区别

字段名 like '%a_'

select * from t3 where name like "a___";

13.正则匹配

使用regexp 关键字

^ $ . [ ] [ ^] | * + {n} {n,m}

select * from t3 where name regexp '^a...$';

14.子查询(嵌套查询)

子查询是将一个查询语句嵌套在另一个查询语句中。

select name,salary from t3 where salary=(select max(salary) from t3);

15.分组查询

GROUP BY :以什么条件分组

GROUP_CONCAT:分组后的数据,显示哪个字段

select sex,group_concat(name) from t3 group by sex;

多表查询

内链接

外链接:左连接、右连接

1.内链接:返回两个表中联结字段相等的行

select a表字段1,a表字段2,... ,b表字段1,b表字段2,... from a表,b表 where a表字段=b表字段;

或者

select a表字段1,a表字段2,... ,b表字段1,b表字段2,... from a表 inner join b表 where a表字段=b表字段;

select name age job_description from A,B where a.a_id=b.b_id;

2.外链接

左连接:left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录

例:select 姓名,年龄,t4.部门编号,部门名称 from t4 left join t5 on t4.部门编号=t5.部门编号;

特点:联结字段值相等的记录,显示完整记录,右表值不等的用null代替;

左表的记录都会显示

右连接:right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录

例:select 姓名,年龄,t5.部门编号,部门名称 from t4 right join t5 on t4.部门编号=t5.部门

编号;

特点:联结字段值相等的记录,显示完整记录,左表值不等的用null代替;

右表的记录都会显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值