数据查询的语法格式:
SELECT [ALL|DISTINCT] {*|<表达式>,…,<表达式>}
FROM <表名>[, <表名>…]
[WHERE <条件表达式>]
[GROUP BY <列名>[, <列名>…][HAVING <谓词>]]
[ORDER BY <列名> [ASC|DESC] [, <列名> [ASC|DESC]…]
查询的结果仍然是一个表
SELECT语句的执行过程为:
- 根据WHERE子句的检索条件,从FROM子句指定的基本表或试图中选取满足条件的元组,再按照SELECT子句中指定的列,投影到结果表中
- 如果有GROUP子句,则将查询结果按照<列名>相同的值进行分组
- 如果GROUP子句后有HAVING短语,则只需输出满足HAVING条件的分组
- 如果有ORDER子句,查询结果还需要按照<列名>的值进行排序
1.单表查询
1.1选择表中的若干列
查询指定的列
- 找出所有老师的名字
select name
from instructor;
- 找出所有教师所在的系名
select dept_name
from instructor;
我们可以发现这里是存在重复的
- 在select后加入关键词distinct,用来删除重复的元组
- 找出所有教师所在的系名,每个系名最多出现一次
select distinct dept_name
from instructor;
- 选出所有属性列
-
- 在SELECT关键词后面列出所有的列名
SELECT ID,name,dept_name,salary
FROM instructor;
- 将<目标列表达式>指定为*
select * from instructor;
- SELECT子句的<目标表达式>可以为:
-
- 算术表达式
- 字符串常量
- 函数
- 列别名
- 例如:将salary的值设置为原来的1.1倍
select ID,name,dept_name,salary*1.1
from instructor;
- 我们将名字大写
select ID,upper(name),dept_name,salary
from instructor;
字符串函数
| 函数 | 作用 |
|---|---|
| CHAR_LENGTH(s) | 返回字符串s的长度 |
| CONCAT(s1,s2,….) | 连接s1,s2…字符串 |
| UPPER(s) | 将字符串s的所有字母都变成大写字母 |
| LOWER(s) | 将字符串s的所有字母变成小写字母 |
| LEFT(s,n) | 返回从字符串s开始的前n个字符 |
| TRIM(s) | 去掉字符串s开始处和结尾处的空格 |
| REPEAT(s,n) | 将字符串s重复n次 |
| REPLACE(s,s1,s2) | 用字符串s2代替字符串s中的字符串s1 |
| REVERSE(s) | 将字符串s的顺序反过来 |
数学函数
| 函数 | 作用 |
|---|---|
| ABS(x) | 返回x的绝对值 |
| RNAD() | 返回0~1的随机数 |
| ROUND(x) | 返回离x最近的整数 |
| POW(x,y), POWER(x,y) | 返回x的y乘方的值 |
| EXP(x) | 返回e的x乘方后的值 |
| MOD(x,y) | 返回x除以y以后的余数 |
| LOG(x) | 返回x的基数为2的对数 |
| LOG10(x) | 返回x的基数为10的对数 |
| SIN(x) | 返回x的正弦 |
- 使用列别名改变查询结果的列标题
select ID,name,dept_name,salary*1.1 as
salary_increase from instructor;
- 加入字符串常量
Select "UC",ID,name,dept_name,salary
from instructor;
1.2选择表中的若干元组
- 查询满足条件的元组
常用的查询条件
- 找出工资在90000美元和100000美元之间的教师的姓名
select name from instructor
where salary between 90000 and 100000;
select name from instructor
where salary<=100000 and salary>=90000;
- 找出所有在computer science 系并且工资超过70000美元的教师的名字
select name from instructor
where dept_name = 'Comp.Sci.' and salary>70000;
这里注意Comp.和Sci.之间有空格
- 找出所有在computer science 和 physics系,并且工资超过70000美元的教师的姓名
select name from instructor
where dept_name = 'Com. Sci.' or 'Physics'
and salary > 70000;
我们可以看到这么写是错误的,我们换种写法
select name from instructor
where dept_name = 'Com. Sci.' or dept_name = 'Physics'
and salary > 70000;
我们可以看到虽然可以运行出结果,但是少了两个人
select name from instructor
where dept_name IN (’Comp. Sci.’, ‘physics’)
and salary >70000;
这里具体是为甚麽,我也不太清楚,如果有明白原因的大佬请在评论区指出~
字符匹配
匹配固定字符串
- 找出工号为76543的教师的详细情况
select * from instructor
where ID = '76543'
后面将会持续更新,希望大家多多支持,点个赞