SQL查询基础

SQL查询基础


前言

  • 数据库查询的一些基础操作:select where 常用的日期函数。

一、SELECT子句

  • 查询记录通过SELECT语句实现,其(精简)语法为:
    SELECT select_expr,... [ FROM table] [ WHERE condition ]
  • 查询表达式语法为:select_expr [ [ AS ] alias ]
  • SELECT语句是完成一次数据查询的完整SQL指令,而SELECT子句是负责定义"返回什么数据"的核心部分。

1.1as别名

  • 语法: SELECT 字段 [as] 别名
  • SELECT 字段,... FROM 表名 [as] 别名

1.2SELECT子句作用

1.3练习

• 计算 10*5的结果

• 查看books 表所有数据

• 提取books 表书名和出版社

• 提取books 表的作者和书名

sql 复制代码
# • 计算 10*5的结果
select 10*5;

#• 查看books 表所有数据
select * from books;

#• 提取books 表书名和出版社
select bname,press from books;

#• 提取books 表的作者和书名

select author ,bname from books;

1.4算术运算

1.5练习

• 查看books表的书名,价格,8折后价格

• 查看books表的书名,价格,价格对2取余的结果

• 查看books表的书名,价格,价格对3整除的结果

sql 复制代码
# • 查看books表的书名,价格,8折后价格
select bname ,price,price*0.8 as discount_price from books;
# • 查看books表的书名,价格,价格对2取余的结果
select bname ,price,price %2 as discount_price from books;
# • 查看books表的书名,价格,价格对3整除的结果
select bname ,price,price div 3 as discount_price from books;

1.6条件运算

  • 语法:IF(expr1,expr2,expr3)

  • 说明: expr1表示的是判断条件,expr2和expr3是符合expr1的自定

    义的返回结果当expr1的值为真时,则返回值为expr2;当expr1的值

    为假时,则返回值为expr3

  • 用法一:需要判断单个字段等于多个固定值时

  • 用法二:WHEN后接独立的条件表达式,复杂逻辑

1.7练习

• 查看books表的书名,作者,价格,折后价格(作者为老舍的8折,

其他九折)

• 查看books表的书名,作者,作者,折后价格(作者为老舍的8折,

鲁迅的7折,矛盾9折,其他作者6折)

• 查看books表的书名,价格,价格奇偶数判断

sql 复制代码
#• 查看books表的书名,作者,价格,折后价格(作者为老舍的8折,其他九折)
select bname,author,price,
      if(author="老舍",price*0.8,price*0.9)  as 折后价格
      from   books;

#• 查看books表的书名,作者,价格,折后价格(作者为老舍的8折,鲁迅的7折,矛盾9折,其他作者6折)
select bname,author,price,
       case author
		    when "老舍" then price*0.8
            when "鲁迅" then price*0.7
            when "矛盾" then price*0.9
            else price*0.6 
		end as 折后价格
        from books;

#• 查看books表的书名,价格,价格奇偶数判断
select bname,price,
       if(price%2,"奇数","偶数") as 价格奇偶性判断
       from books;

二、WHERE子句

  • WHERE子句用于规定选择的标准
  • 如需有条件地从表中选取数据,可将WHERE子句添加到SELECT语句。

2.1比较运算

2.2条件查询训练

• 图书价格>50的图书所有信息

• 图书价格不等于41的图书所有信息

• 备注为空的图书

• 备注不为空的图书

sql 复制代码
#• 图书价格>50的图书所有信息
select * 
from books
where price>50;


#• 图书价格不等于41的图书所有信息
select * 
from books
where price!=41;


#• 备注为空的图书
select * 
from books
where common is null;

#• 备注不为空的图书
select * 
from books
where common is not null;

2.3 逻辑运算

2.4 训练

• 图书价格40-50元的图书(and 和 between and分别实现)

• 鲁迅或老舍的图书(or 和 in 分别实现)

• 价格不在40-50元的图书(or 和 not between and 分别实现)

• 不是鲁迅或老舍的图书(and 和 not in 分别实现)

sql 复制代码
#• 图书价格40-50元的图书(and 和 between and分别实现)
select *
from books
where price>=40 and
      price<=50;
      
select *
from books
where price between 40 and 50;

#• 鲁迅或老舍的图书(or  和 in 分别实现)
select *
from books
where author="鲁迅" or
      author="老舍";
      
      
select *
from books
where author in ("鲁迅", "老舍");

#• 价格不在40-50元的图书(or 和 not between and 分别实现)
select *
from books
where price<40 or
      price>50;
      
select *
from books
where price not between 40 and 50;
#• 不是鲁迅或老舍的图书(and 和 not in 分别实现)

select *
from books
where author!="鲁迅" and
      author!="老舍";
      
      
select *
from books
where author not in ("鲁迅", "老舍");

2.5逻辑运算注意事项

  • AND中只要有一个条件是0(假),结果必为0(假);只有全为1(真)
    才是1,否则可能是NULL
  • OR中只要有一个条件是1(真),结果必为1(真);只有全为0(假)才
    是0,否则可能是NULL
  • 多个OR条件(同一字段)可简化为IN

2.6运算级优先级

先算数,再比较,最后逻辑

2.7练习

• 查找40多元的图书

• 查找人民教育出版社出版的图书

• 查找老舍写的,中国文学出版社出版的图书

• 查找备注不为空的图书

• 查找价格超过50元的图书,只看书名和价格

• 查找鲁迅写的或者茅盾写的图书

sql 复制代码
#• 查找40多元的图书
select *
from books
where price between 40 and 49;

#• 查找人民教育出版社出版的图书 
select *
from books
where press = "人民教育出版社";


#• 查找老舍写的,中国文学出版社出版的图书 
select *
from books
where press = "中国文学出版社" and
	  author = "老舍";


#• 查找备注不为空的图书
select * 
from books
where common is not null;

#• 查找价格超过50元的图书,只看书名和价格
select bname,price
from books
where price>50;
      

#• 查找鲁迅写的或者茅盾写的图书

select *
from books
where author in ("鲁迅", "茅盾");

三、常用日期函数

3.1系统时间

  • CURDATE() 或CURRENT_DATE() 返回当前的日期
  • CURTIME()或CURRENT_TIME() 返回当前的时间
  • NOW() 返回当前的日期和时间

3.2时间计算

  • DATE_ADD(date,INTERVAL int keyword),返回日期date加上间隔时间int的结果
    (int必须按照关键字进行格式化),如:SELECT
  • DATE_ADD(CURRENT_DATE,INTERVAL 6 MONTH);
  • DATE_SUB(date,INTERVAL int keyword),返回日期date加上间隔时间int的结果
    (int必须按照关键字进行格式化),如:SELECT
  • DATE_SUB(CURRENT_DATE,INTERVAL 6 MONTH);
  • DATEDIFF(结束日期,开始日期),计算两个日期天数之差
  • TIMESTAMPDIFF(unit,开始日期,结束日期),计算两个日期unit之差,unit 包含
  • SECOND:秒 MINUTE:分钟HOUR:小时 DAY:天 WEEK:星期 MONTH:月
    QUARTER:季度 YEAR:年

3.3时间类型转换

  • UNIX_TIMESTAMP(date/datetime) 把日期/日期时间字段转换为时间戳
  • FROM_UNIXTIME(timestamp,fmt) 根据指定的fmt格式,格式化UNIX时间戳为日期格式 ,
    默认%Y-%m-%d %H:%i:%s
  • DATE_FORMAT(date/datetime/timestamp,fmt) 依照指定的fmt格式格式化
  • 日期时间:
  • 支持格式:'YYYY-MM-DD' 'YYYY-MM-DD HH:mm:ss' 'YYYYMMDD'(如 '20251203');
  • 不支持格式:'MM/DD/YYYY'(如 '12/03/2025')、'YYYY年MM月DD日',需先通过
    STR_TO_DATE() 转换SELECT STR_TO_DATE('12/03/2025', '%m/%d/%Y')

3.4格式符

3.5提取时间函数

  • DATE(datetime/timestamp) 提取日期时间/时间戳的日期部分
  • YEAR(date) 返回日期date的年份(1000~9999)
  • QUARTER(date) 返回date在一年中的季度(1~4),如SELECT QUARTER(CURRENT_DATE);
  • MONTH(date) 返回date的月份值(1~12)
  • WEEK(date) 返回日期date为一年中第几周(0~53)
  • DAYOFWEEK(date) 返回date所代表的一星期中的第几天(1~7)
  • DAYOFMONTH(date) 返回date是一个月的第几天(1~31)
  • DAYOFYEAR(date) 返回date是一年的第几天(1~366)
  • HOUR(time) 返回time的小时值(0~23)
  • MINUTE(time) 返回time的分钟值(0~59)

3.6尝试实现函数:

sql 复制代码
select curdate();
select curtime();
select now();
select date_add(curdate(),interval 2 day);
select date_sub(curdate(),interval 4 day);
select datediff("2024-5-21" ,"2023-8-1");
select timestampdiff(day,"2023-8-1","2024-5-21" );
select unix_timestamp(curdate());
select unix_timestamp(curtime());
# 按照指定格式化日期
select from_unixtime(1766543860,"%Y%m%d");
select date_format(curdate(),"%y/%m/%d");

select date_format(curtime(),"%H:%i:%s");
select date(now());
select date("2025-7-1 07:37:29");

select  year("2025-7-1");
select month("2025-7-1");
select hour("2025-7-1");
select quarter("2025-7-1");

select dayofweek(curdate());

3.7综合训练

• 计算每个人报名比赛的年龄 (比赛日期-生日)

• 找到前几个月过生日的人(当前月-n = 出生月)

• 未来15天内过生日的人

• 数据准备如下

• create table marathon (

• id int primary key auto_increment,

• athlete varchar(32),

• birthday date,

• r_time datetime comment "报名时间",

• performance time

• );

• insert into marathon values

• (1,"曹操","1998-2-16","2021/5/6 10:10:27","2:38:49"),

• (2,"关羽","2000-7-19","2021/4/30 16:22:09","2:27:18"),

• (3,"孙策","1995-10-23","2021/5/2 20:1:2","2:44:00");

sql 复制代码
create table marathon (
 id int primary key auto_increment,
 athlete varchar(32),
 birthday date,
 r_time datetime comment "报名时间",
 performance time
 );
insert into marathon values
(1,"曹操","1998-2-16","2021/5/6 10:10:27","2:38:49"),
(2,"关羽","2000-7-19","2021/4/30 16:22:09","2:27:18"),
(3,"孙策","1995-10-23","2021/5/2 20:1:2","2:44:00");

select athlete,
       timestampdiff(year,birthday,r_time) as年龄
	   from marathon;

select * 
from marathon 
where month(birthday) >= month(date_sub(now(),interval 6 month));
# 这里为了方便实现的逻辑不对大概熟悉函数就行
select * 
from marathon 
where day(birthday) <=
day(date_add(now(),interval 24 day));

总结

• 本章节主要内容是Select、Where子句

• 算数、条件、比较、逻辑四类运算

• 常用日期函数:系统时间、时间计算、类型转换、提取单位

相关推荐
fjkxyl2 小时前
Redis 跳表技术博客:为什么不选用红黑树和 B+ 树
数据库·redis·缓存
张人玉2 小时前
整合 Sugar ORM 连接 SQLite 数据库到 WPF 折线图项目
数据库·sqlite·c#·wpf
、BeYourself2 小时前
PGvector :在 Spring AI 中实现向量数据库存储与相似性搜索
数据库·人工智能·spring·springai
a187927218312 小时前
MySQL 硬件优化和操作系统优化
数据库·mysql·优化·raid·numa·sysbench·系统参数
linweidong2 小时前
hive sql行转列,列转行sql的实例
hive·hadoop·sql
只想早点退休的90后2 小时前
sql面试题分享
数据库·sql
枫叶丹42 小时前
【Qt开发】Qt系统(三)->事件过滤器
java·c语言·开发语言·数据库·c++·qt
不会c嘎嘎2 小时前
mysql -- 使用CAPI访问mysql服务器
服务器·数据库·mysql
Zzzzmo_2 小时前
【MySQL】数据类型 及 表的操作
数据库·mysql
L1624762 小时前
linux系统中YUM安装MySQL数据库详细教程
linux·数据库·mysql