常用SQL语句汇总

时间:2022-09-16 19:12:13

常用SQL语句

非增删改查的部分

  1. 创建数据库
    sql
    create database "db.tan"
  2. 创建模式
    sql
    create schema "xxx"
  3. 创建表
    sql
    create table "xxx"
  4. 创建视图
    sql
    create view "xxx"
  5. 创建索引
    sql
    create index "xxx"

    说明:上面这五种创建,删除都是使用 drop 关键字
    模式:模式也称为逻辑模式,是数据库中全体数据的逻辑结构和特征的描述,是所有用户的公关数据视图。

表的定义、删除与修改

  1. 基本表的定义
    sql
    create table "表名" (
    "列名1" "数据类型" "完整性约束条件",
    "列名2" "数据类型"
    );
  2. 基本表的修改 alter
    sql
    alter table "表名" add "新列名" 数据类型
    alter table "表名" drop "新列名" 数据类型
    alter table "表名" change "列名" "新列名" 新数据类型 ;
  3. 基本表的删除
    sql
    drop table 表名 ;
  4. 设置主外键
    sql
    alter table 表名 add **constraint** 约束名 foreign key(主键) references 外表(外表的属性);
    ALTER TABLE employee ADD FOREIGN KEY(dept_id) REFERENCES department(id);

数据的增删改查

查询的通用格式

    select 列名1,列名2
from 表名或者视图名 [as 列名]
where 条件表达式
group by <列名> having <条件表达式>
order by <列名> asc||desc

单表查询

选择表中的若干列

```sql
1、查询指定列
select sno,sname from student;
2、查询全部列
select * from student;
3、查询经过计算的值
select sname,2017-sage from student;
4、目标表达式
select sname,'year of birth:',2017-sage,lower(sdept);
```

选择表中的若干元组

    1、消除表中重复的行
select distinct sno from sc;
2、查询满足条件的元组
比较 =,>,<,>=,<=....not + 比较符
确定范围 between xx and xxx;这里是包括上下边界的值的,not between xxx and xxx;
确定集合 in,not in
字符串匹配 like ,not like;
空值 is null,is not null
多重条件 and,or,not;
3、涉及到空值的查询
select sno,cno
from sc
where grade is null;

4、多重条件
用 and 或 or 来连接多个查询条件,and 的优先级高于 or ,但是可以用括号来改变。

order by (排序)控制升序或者降序

    select sno,grade
from sc
where cno = '3'
order by grade desc;
// desc降序 asc升序

group by 分组

group by 字句将查询结果按一列或者多列的值分组,值相等的为一组,分组后聚集函数将作用于每一个组,即每一个组都有一个函数值。

    // 查询选修了三门以上课程的学生的学号
select sno
from sc
grop by sno
having count(*) > 3 ;

where和having的有区别的:
主要在于作用的对象不同:
1、where字句作用于基本表或者视图,从中选择满足条件的元组
2、having作用于组,从中选择满足条件的组

聚集函数

    count(*);     //统计元组的个数
count( [distinct] <列名>); // 统计一列中值的个数
sum( [distinct] <列名>); //计算一列值的总和,(数值的总和)
avg( [distinct] <列名>); //计算一列值的平均值,(数值的平均)
max([distinct] <列名>);
min([distinct] <列名>);
// 当聚集函数遇到空值时,除了count*()外,其它都跳过控制而只处理非空值。
where字句中不可使用聚集函数,聚集函数只能用于selecthaving后面。