一、数据库基础概念
-
数据库(Database):存储和管理数据的容器。
-
数据表(Table):以行和列形式组织数据。
-
行(Row):一条记录。
-
列(Column):字段,描述数据的属性。
-
主键(Primary Key):唯一标识一条记录,不能为空、不可重复。
-
外键(Foreign Key):保证引用完整性,用于建立表之间的关系。
-
索引(Index):提高查询效率的结构,分为聚集索引和非聚集索引。
二、SQL 基本语句
1. 数据查询(DQL)
-
select 基本用法
select Name, Age from Students where Age > 18 order by Age desc;
-
常见子句
-
where
:行筛选 -
group by
:分组统计 -
having
:分组后条件过滤 -
order by
:排序(asc 升序,desc 降序) -
top / offset fetch
:分页
-
2. 数据操作(DML)
-
插入数据
insert into Students(Name, Age) values('张三', 20);
-
修改数据
update Students set Age = Age + 1 where Name = '张三';
-
删除数据
delete from Students where Age < 18;
3. 数据定义(DDL)
-
创建表
create table Students( Id int identity(1,1) primary key, Name nvarchar(50) not null, Age int default(18) );
-
修改表结构
alter table Students add Gender nvarchar(10);
-
删除表
drop table Students;
4. 数据控制(DCL)
-
授权
grant select, insert on Students to UserA;
-
回收权限
revoke insert on Students from UserA;
三、常见约束
-
primary key:主键,唯一且非空。
-
foreign key:外键,保证数据引用完整性。
-
unique:唯一性约束。
-
not null:非空约束。
-
default:默认值。
-
check:检查条件。
四、重要函数
-
聚合函数:
count
、sum
、avg
、max
、min
-
字符串函数:
len
、substring
、concat
-
日期函数:
getdate()
、dateadd()
、datediff()
-
数学函数:
abs()
、round()
、rand()
五、分页查询
1. OFFSET FETCH(SQL Server 2012+)
select * from Students order by Id offset 20 rows fetch next 10 rows only; -- 第3页,每页10条
2. ROW_NUMBER()
select * from ( select row_number() over(order by Id) as RowNum, * from Students ) t where t.RowNum between 21 and 30;
六、事务与锁
-
事务(Transaction):保证一组操作要么全部成功,要么全部失败。
- 四大特性(ACID):原子性、一致性、隔离性、持久性。
-
事务控制语句:
begin transaction; update Accounts set Balance = Balance - 100 where Id = 1; update Accounts set Balance = Balance + 100 where Id = 2; commit; -- 提交事务 rollback; -- 回滚事务
七、索引
-
聚集索引(Clustered Index):数据行按照索引顺序存储,每个表只能有一个。
-
非聚集索引(Non-Clustered Index):单独存储索引结构,表可有多个。
-
优点:提高查询速度。
-
缺点:插入、更新、删除性能可能降低。
八、delete / truncate / drop 区别
-
delete:删除数据,可加条件,保留表结构,自增列不重置。
-
truncate:快速清空数据,不能加条件,自增列会重置。
-
drop:直接删除整个表(数据 + 结构)。
九、union 与 union all
-
union
:合并查询结果并去重。 -
union all
:合并查询结果,不去重,效率更高。
🔑 总结
数据库核心内容主要围绕 SQL 语句、约束、函数、事务、索引 展开。
考试和面试常考点:
-
delete / truncate / drop
区别 -
group by / having
区别 -
外键作用
-
分页查询写法
-
事务四大特性
-
聚集索引 vs 非聚集索引