流程控制函数

本文介绍了SQL中的一些关键查询技巧,包括使用IFNULL和IF函数处理空值,CASE语句进行条件判断,分页查询的方法,以及如何统计特定情况的记录数。此外,还展示了如何通过子查询实现数据比较,复制表记录以及删除重复数据的步骤。最后,讨论了UNION和UNION ALL在合并查询中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 流程控制函数

SELECT username ,IFNULL(balance,120) from user

IFNULL(balance,120)        balance不为空时返回balance,为空时返回120

 SELECT username ,IF(balance is NULL,120,balance) from user

IF(balance is NULL,120,balance)     balance是空时,返回120,否则返回balance

 SELECT username ,(SELECT CASE when balance >100 then '超重' when balance <80 then '超轻' else '正常' end) as `type`from user

如果user表体重大于100则显示超重,如果是体重小于80则显示超轻,其他显示正常

分页查询

select ....limit start,rows 表示从start+1行开始取,取出rows行,start从0开始计算

select * from emp order by empno limit 每页显示记录数*(第几页-1),每页显示记录数

按照id号升序取出,每页显示3条记录,请分别显示第1页,第2页,第3页

SELECT * FROM user order by id LIMIT 0,3;

SELECT * FROM user order by id LIMIT 3,3;

SELECT * FROM user order by id LIMIT 6,3;

统计没有获取补助的雇员数

select count(*),count(IF(comm is null,1,null)) from emp

select count(*),count(*)-count(comm) from emp

先对age去重之后再对age进行统计

 SELECT count(DISTINCT age) from user;

select  语句顺序:

 select column1,column2    from table 

group by column

having condition

order by column

limit start,rows;

 多列子查询

查询与ALLEN的部门和岗位完全相同的所有雇员并且不含ALLEN本人

SELECT * FROM emp WHERE ( deptno, job )=(

SELECT deptno, job FROM emp WHERE ename = 'ALLEN'


AND ename != 'ALLEN'

表 自我复制

1、把goods表的记录复制到good

insert into good (id,price) select p_id,price from goods

2、自我复制

非主键的时候才能实现

insert into good select * from good

如何删除掉一张表重复记录

1、先创建一张表good_01

CREATE table good_01 like good;

2、让good_01有重复的记录

insert into good_01 SELECT * from good

3、考虑去重思路:

(1)思路先创建一张临时表good_tmp,该表good_tmp的结构和表good_01一样

CREATE table good_tmp like good_01

(2)把good_01的记录,通过distinct关键字处理后把记录复制到good_tmp

INSERT into good_tmp select  DISTINC * from good_01

(3)清楚掉good_01记录

delete from good_01

(4)把good_tmp表的记录复制到good_01

INSERT into good_01 select * from good_tmp

(5)drop掉临时表good_tmp

drop table good_tmp

合并查询

 union all 

就是将两个查询结果合并,不会去重

select instock from goods where price >60
UNION all
select instock FROM goods where onsale>3

union 就是自动将去掉结果集中重复行

select price,instock from goods where price >60
UNION 
select price,instock FROM goods where onsale>3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值