DQL 数据查询 select

一、基础查询

1. 查询指定列

语法

sql 复制代码
select 字段名1,字段名2 from 表名;

示例

sql 复制代码
select stu_name,stu_age from stus where stu_age>20;

2. 计算列

可以直接对字段进行算术运算展示结果

sql 复制代码
select stu_name,2021-stu_age from stus;

3. as 设置字段别名

给查询列设置别名,as 关键字可以省略

sql 复制代码
select stu_name,2021-stu_age as stu_birth_year from stus;
select stu_name as 姓名,2021-stu_age as 出生年份 from stus;

4. distinct 消除重复行

sql 复制代码
-- 原始查询,包含重复年龄
select stu_age from stus;
-- 去除重复数据
select distinct stu_age from stus;

二、where 条件查询:比较运算符

sql 复制代码
-- = 等于
select * from stus where stu_num = '20230101';

-- != 、<> 不等于(两种写法等价)
select * from stus where stu_num != '20230101';
select * from stus where stu_num <> '20230101';

-- > 大于
select * from stus where stu_age>18;

-- < 小于
select * from stus where stu_age<20;

-- >= 大于等于
select * from stus where stu_age>=20;

-- <= 小于等于
select * from stus where stu_age<=20;

-- between and 区间查询,闭区间 [最小值,最大值]
select * from stus where stu_age between 18 and 20;

三、where 逻辑运算符 and or not

sql 复制代码
-- and 并且:所有条件同时满足
select * from stus where stu_gender='女' and stu_age<21;

-- or 或者:满足任意一个条件即可
select * from stus where stu_gender='女' or stu_age<21;

-- not 取反
select * from stus where stu_age not between 18 and 20;

四、like 模糊查询

通配符说明

%:匹配任意数量字符(0个、1个、多个)

_:只匹配单个字符

sql 复制代码
-- 查询姓名包含张
select * from stus where stu_name like '%张%';

-- 查询姓名以张开头
select * from stus where stu_name like '张%';

-- 查询姓名以三结尾
select * from stus where stu_name like '%三';

-- 查询第二个字符为三
select * from stus where stu_name like '_三%';

五、order by 排序

语法

sql 复制代码
select * from 表名 where 条件 order by 字段 asc|desc;

asc 升序(默认,可以不写);desc 降序

sql 复制代码
-- 单字段排序
select * from stus where stu_age>15 order by stu_gender desc;

-- 多字段排序
-- 优先第一个字段排序;第一个字段值相同,再按第二个字段排序
select * from stus where stu_age>15 order by stu_gender asc,stu_age desc;
相关推荐
勤奋的树懒4 小时前
从手写 SQL 到 Windows 工具:致远 OA 文件清理实践
数据库·sql·windows server·致远oa
cspttty11 小时前
2026秋招供应链分析师技能栈:SQL、Excel、BI与业务分析
数据库·sql·excel
子非鱼a1 天前
【WEB】[GXYCTF2019]BabySQli
sql
todoitbo1 天前
SQL Server数据库迁移:V9R4C019 如何接住存量 T-SQL 批处理
数据库·sql·国产数据库
写后端的胖头鱼1 天前
【高频面试题】SQL 查询慢怎么排查
数据库·sql·mysql·oracle·慢查询·高频面试题
小程序设计1 天前
基于SQL与漏斗模型的社群App优化研究
数据库·sql
SelectDB技术团队1 天前
从 ClickHouse 迁移到 Doris:SQL 兼容、同步与验证清单
数据库·人工智能·sql·clickhouse·apache doris·selectdb·湖仓架构升级
leo_messi941 天前
Mysql学习(十二) -- SQL执行到底做了什么事?
sql·学习·mysql
babe小鑫2 天前
精算学专业秋招:Excel、SQL、R和Python应该先练什么
sql·r语言·excel
2501_933670792 天前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql