SQL语言基础

一、SQL简介

SQL(Structured Query Language)结构化查询语言是广泛应用于数据库管理软件的语言(非编程语言),根据SQL语言不同功能特性,将其分为三类,分别是DDL(Data Definition Language)数据定义语言,DML(Data Maniputation Language)数据操纵语言,DCL(Data Control Language)数据控制语言。

二、SQL语言基础

1. 数据定义语言

功能:用于数据库,表,视图,函数,存储过程或其他对象的创建(create),修改(alter),删除(drop)

(1)创建数据库并设置默认字符集为UTF-8 

create database [数据库名] default charset [字符集];

(2)删除数据库

drop database [数据库名];

(3)创建表

create table [表名](字段名1 字段类型,字段名2 字段类型,...)

(4)删除表

drop table [表名]

(5)修改表-表中增加一行字段

alter table [表名] add column [字段名] [字段类型]

(6)修改表-表中删除一行字段

alter table [表名] drop column [字段名] 

(7)修改表-字段类型/位置

alter table [表名] modify [字段名] [字段类型] after [上一个字段名]

(8)修改表-字段名/字段类型/位置

alter table [表名] change [原字段名] [新字段名] [新字段类型] after [上一个字段名]

(9)修改表名

alter table [原表名] [新表名]

补充:

主键:primary key(字段名)

外键:foreign key(字段名) reference [表名](字段名)

主外键可以在创建表时直接加在字段类型后,或者后期通过alter add设置主外键,取消主外键用alter drop

 

2. 数据操纵语言

功能:用于表,视图等对象的增加(insert),删除(delete),修改(update),查询(select)等操作

1. 表中插入一条数据(INSERT+VALUES/INSERT+SELECT/INSERT+SET)

2. 删除表中的一条数据(根据需要加where条件)

删除表中所有数据

3. 删除多个表中的关联数据

4. 更新表中的一条数据

更新表中的所有数据

5. 查询表

(1) 查询表中所有数据 select * from users;

(2) 根据条件查询表中某条数据 select * from users where uid=1000;

(3) 查询表中某条数据的指定字段 select uname,passwd from users where uid=1000;

(4) 根据第2列进行排序(默认升序),desc控制降序排列 select * from users order by 2;

(5) 子查询

IN的使用:select * from users where uid in(select uid from users2);

等价于select * from users a where exists(select uid from users2 b where a.uid=b.uid)

EXISTS的使用:select * from users where uid exists(select uid from users2);

(6) 关联查询(内查询,左查询,右查询)

select a.uname b.mobile from users a inner/left/right join users2 b on a.uid=b.uid

演示:

users和users2表数据展示

内查询

左查询

右查询 

(7)联合查询

select * from users union select * from users2 //去重

select * from users union all select * from users2 //不去重

select uid,uname from users union select 1,’michael’;  //数据拼接

 

3. 数据控制语言

功能:用于用户权限管理等

基本使用:grant [insert/select/update/delete] privileges on *.* to [用户名]@[登陆IP] identified by [密码]

1. 创建一个任意IP登陆的超级管理员权限用户

 


版权声明:本文为Sck121原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。