SQL:結(jié)構(gòu)化查詢語言
SQL語言分類
- DDL:數(shù)據(jù)定義語言囤捻。
- DML:數(shù)據(jù)操作語言藕施。
- DQL:數(shù)據(jù)查詢語言固翰。
數(shù)據(jù)庫操作
- 創(chuàng)建數(shù)據(jù)庫 [變量] (可省略)
create database [數(shù)據(jù)庫名稱] (character set [gbk/utf-8])一膨;
字符集默認(rèn)值是utf-8
- 刪除數(shù)據(jù)庫
drop database [數(shù)據(jù)庫名稱];
- 查看數(shù)據(jù)庫
查看所有數(shù)據(jù)庫:show databases;
查看數(shù)據(jù)庫定義信息: show create database [數(shù)據(jù)庫名稱];
- 其他數(shù)據(jù)庫命令
切換使用的數(shù)據(jù)庫: use [數(shù)據(jù)庫名稱];
查看正在使用的數(shù)據(jù)庫:select database();
表的操作
- 單表約束
- 主鍵約束:primary key ,要求被修飾的字段:唯一 非空诞仓。
- 唯一約束:unique,要求被修飾的字段唯一。
- 非空約束:not null 要求被修飾的字段不能為空赁温。
- 創(chuàng)建表
create table [表名](
id int(長度) [約束]坛怪,
淤齐。。袜匿。更啄。
);
- 查看表
查看數(shù)據(jù)庫中的所有表:show tables;
查看表的結(jié)構(gòu):desc [表名];
- 刪除表
drop table [表名];
- 修改表
給表添加一列:alter table [表名] add [列名](長度)[約束]居灯;
修改表中列的類型祭务、長度和約束:alter table [表名] modify 列名 類型(長度) 約束;
修改表的列名:alter table 表名 change 舊列名 新列名 類型(長度)約束怪嫌;
刪除表的列:alter table 表名 drop 列名义锥;
修改表名: rename table 表名 to 新表名;
修改表的字符集:alter table 表名 character set 字符集岩灭;
插入數(shù)據(jù)語句 (增)
對(duì)應(yīng)插入數(shù)據(jù):insert into 表名(列名1拌倍,列名2,列名3) values(值1噪径,值2柱恤,值3);
插入所有數(shù)據(jù) : insert into 表名 values(值1,值2找爱,值3);
刪除數(shù)據(jù)語句(刪)
delete from 表名[where條件]
更新數(shù)據(jù)語句(改)
update 表名 set 字段名=值梗顺,字段名=值。缴允。荚守。where條件;
查詢數(shù)據(jù)語句(查)
先建一個(gè)表
- 簡單查詢
查詢所有人信息:select * from person;
查詢姓名和年齡:select pname,age from person;
- 別名查詢 as關(guān)鍵字 可省略
表別名 查詢所有數(shù)據(jù):select * from person as p;
列別名 查詢姓名: select pname as pn from person;
- 去重復(fù)查詢 關(guān)鍵字:distinct
查詢所有時(shí)間去重復(fù)后的數(shù)據(jù):select distinct pdate from person;
- 帶運(yùn)算查詢
查詢年齡+10的人數(shù)據(jù): select pname,age+10 from person;
條件查詢
以此類推 :
查詢年齡大于24的人:select * from person where age>24;
- 更多用法
eg:
- like的用法
- in的用法
- between and
- 排序 關(guān)鍵詞:order by asc升序 desc降序
按年齡由高到低排序:select * from person order by age desc;
- 聚合函數(shù)
sum() 求和.
avg()求平均數(shù)
max()最大值
min()最小值
count()個(gè)數(shù)
求年齡之和:select sum(age) from person;
求人數(shù)的個(gè)數(shù): select count(*) from person;
- 分組
先添加班級(jí)信息。
添加班級(jí)列:alter table person add class int;
將所有人分到1班:update person set class=1;
將pid為135的分到2班:UPDATE person SET class = 2 WHERE pid IN (1,3,5);
查看每個(gè)班級(jí)的平均年齡:SELECT class,avg(age) FROM person GROUP BY class;