SQL基础学习
SQL简介
SQL是一个结构化查询语言,用于和数据库通信的语言,不是某个数据库软件特有的,而是几乎所有的主流数据库软件通用的语言。
常见的数据库管理系统
mysql、 oracle、 db2、 sqlserver
SQL语法
SQL可分为四类
DML(数据操纵语言)
用来对数据库中的表进行增删改操作。 关键字:insert,delete,update等。
DDL(数据定义语言)
用来定义数据库对象:数据库,表,列等。 关键字:create,drop, alter等。
DQL(数据查询语言)
用来查询数据库中表的记录(数据)。 关键字:select, where等
DCL(数据控制语言)
用来定义数据库的访问控制权限和安全级别,及创建用户。关键字: grant, revoke等
基础语句
1.select
查询某一个字段
select 字段名 from 表名
查询所有字段
select * from 表名
2.distinct
对于某个字段去重复值
select distinct 字段 from 表名
注意:distinct 必须放在开头
select id,distinct name from A;会提示错误
3.where子句
从查询的表中根据条件来筛选数据
select 字段 from 表名 where 字段 运算符 值
常用运算符
操作符 | 描述 |
---|---|
= | 等于 |
<> | 不等于 |
> | 大于 |
< | 小于 |
>= | 大于等于 |
<= | 小于等于 |
and | 与 |
or | 或 |
between | 在某个范围内 |
like | 模糊查询 |
例:查询名字为张三的人
select * from A where name='张三'
4.order by 语句
根据指定的字段对结果进行排序
默认是升序(asc) 降序是使用(desc)
查询某个字段,对结果按照升序排序
select 字段 from 表 order by 字段 desc
查询A,B字段,对结果按照A字段升序B字段降序排序
select A,B from 表名 order by A asc,B desc
5.insert into 语句
用于向表格中插入新的行
insert into 表名 values(值1,值2,....)
指定要插入数据的列
insert into 表名(列1,列2,...) values(值1,值2,...)
例:插入新的行
原student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
insert into student values('03','王五','90')
插入后student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
03 | 王五 | 90 |
例:在指定列中插入数据
原student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
insert into student (id,name) values('03','王五')
插入后student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
03 | 王五 |
6.update 语句
用于修改表中的数据
update 表名 set 列名 = 新值 where 列名 = 某值
student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
更新某一行中的一个列
update student set name ='王五' where id = 02
结果
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 王五 | 100 |
更新某一行中的若干列
update student set id = 03,name = '王五',score = 90
结果
id | name | score |
---|---|---|
01 | 张三 | 90 |
03 | 王五 | 90 |
7.delete 语句
用于删除表中的行
delete from 表名 where 列 = 值
student表
id | name | score |
---|---|---|
01 | 张三 | 90 |
02 | 李四 | 100 |
删除某行
delete from student where name = '李四'
结果
id | name | score |
---|---|---|
01 | 张三 | 90 |
删除所有行
delete from 表名
或者
delete * from 表名