一、數據庫基礎概念
數據庫(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 非聚集索引