数据库13:查询语句

数据库

十三、查询语句

SELECT: 字段表达式

  • SELECT 既可以做查询, 也可以做输出
  • 示例
select rand();  -- 随机数
select unix_timestamp(); -- 显示Unix时间戳
select id, name from student;

FROM 子句

  • 语法: select 字段 from 表名;
  • FROM 后面是数据源, 数据源可以写多个, 数据源一般是表明, 也可以是其他查询的结果
  • 示例
SELECT student.name, score.math FROM student, score;

WHERE 子句: 按指定条件过滤

  • 语法: select 字段 from 表名 where 条件;
  • WHERE 是做条件查询, 只返回结果为 True 的数据
  • 示例
select name from student where city = '上海';
  • 空值判断:is null | is not null
select `name` from `student` where `description` is
null;
select `name` from `student` where `description` is not
null;
  • 范围判断:
    – between … and …
    – not between … and …
select id, math from score where math between 60 and 70;
select id, math from score where math not between 60 and
70;
select * from score where math>=80 and english<=60;  --
直接做比较判断

GROUP BY: 分组查询

  • 按照某一字段进行分组, 会把该字段中值相同的归为一组, 将查询的结果分类显示, 方便统计。
  • 如果有 WHERE 要放在 WHERE 的后面
  • 语法: select 字段 from 表名 group by 分组字段;
  • 示例
select sex, count(id) from student group by sex;
-- 在group将需要的结果通过 “聚合函数” 拼接
select sex, group_concat(name) from student group by
sex;
-- 添加where语句
-- 按性别分组, 将上海地区的男生女生姓名连接起来
select sex, group_concat(name) from student where
city='上海' group by sex;

HAVING

  • HAVING 与 WHERE 在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与聚合函数一起使用
  • 语法: SELECT 字段 FROM 表名 HAVING 条件;
  • WHERE: 后面不能加上聚合函数,只能写在.数据源的后面
  • HAVING: 条件字段必须要在结果集中出现, HAVING 可以写在 GROUP BY的后面
  • 示例:
select `name`, `birthday` from `student` where
`birthday` > '1995-1-1';
select `name`, `birthday` from `student` having
`birthday` > '1995-1-1';
select `name` from `student` where `id` >= 5;
select `name` from `student` having `id` >= 5;  -- 错误
select * from student where id>=3 and city='北京';
select * from student having id>=3 and city='北京';
select * from student where id>=3 having city='北京';  --
混用
-- 取出每个城市中满足最小出生年份大于1995的
select city, group_concat(birthday) from student group
by city having min(birthday) > '1995-1-1';

ORDER BY: 按字段排序

  • ORDER BY 主要作用是排序
  • ORDER BY 写在 GROUPBY 后面 ,如果有 HAVING 也要写在 HAVING 的后面
  • 语法: select 字段 from 表名 order by 排序字段 asc|desc;
  • 分为升序 asc 降序 desc, 默认 asc (可以不写)
  • 示例
select * from student order by age;
select * from student order by age desc;

LIMIT: 限制取出数量

  • 语法
select distinct city from student;

dual表

dual 是一个虚拟表, 仅仅为了保证 select … from … 语句的完整性

select now() from dual
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值