操作数据库要使用 SQL 语言:
创建表
create table 表名{ 字段名(列名) 字段类型(长度) [约束], ....... }
– 约束:
– 主键约束: 这一列是主键列(非空和唯一) primary key
– 唯一约束: 这一列不能重复。 unique
– 非空约束: 这一列不能不设置值。 not null
比如:
create table student(
id int(11) primary key,
name varchar(255) not null,
card varchar(64) unique
)
-- 查看当前数据库下的表
show tables;
-- 查看某个表中的列信息
desc 表名称;
-- 查看某个表的建表语句
show create table 表名称;
-- 物理删除某张表
drop table 表名称;
-- 添加列:
alter table 表名称 add 列名 类型(长度) 约束;
-- 修改长度及约束
alter table 表名 modify 列名 类型(长度) 约束;
-- 修改列的名字
alter table 表名 change 旧的列名 新的列名 类型(长度) [约束];
-- 删除列
alter table 表名 drop 列名;
-- 重命名表
rename table 表名称 to 新的名称;
insert into 表名 (列名1,......) values (值1,.....);
-- 批量插入
insert into 表名 (列名1,....)
select 语句(列要对应)
update 表名 set 字段1 =值1 , ..... where 条件;
-- 比如:amount列统一增加 50
update order2 set amount=amount+50;
-- 清空id=3 的数据的 amount 列的值
update order2 set amount=null where id =3;
delete from 表名 where 条件;
-- 查询所有
select * from 表名
-- 查询一部分列
select 列1,.... from 表名
-- 查询的同时指定新的列名
select 列1 as 列名1,..... from 表名 -- as 可以省略
-- 查询还可以指定常量、及简单的计算
select 列1,常量,列2*1.1 from 表名
select id,create_time createTime,`user`,amount*1.1 as price, 1 as status from order2
-- 还可以配合distinct 关键字来去重
select distinct 列1 from 表名
可以用在: 更新【update】、删除【delete】、查询【select】
-- 可以出现的内容:
-- 关系: > 大于
-- < 小于
-- = 等于 【注意】
-- <> 不等于 【注意】
-- >= 大于等于
-- <= 小于等于
-- between ... and ..... 【适用于数字和日期】 介于 xxx 和 yyy 之间 【既包含开头,也包含结束】
select * from `order` where create_time BETWEEN '2020-07-15' and '2020-07-31'
-- in(集合) 表示在那个范围内
select * from `order` where id in(3,6,7,10)
-- 称为子查询:是我们初期解决sql问题的一大神器。
select * from `order` where id in(
select id from `order2`
)
-- like 模糊查询: 有两个特殊的字符 _ 表示一个字符 % 表示任意个(0个或多个)字符
-- is null 为null
-- is not null 不为null
-- 另外,这些条件可以使用 小括号 来分组优先级。以及 AND【并且】 OR【或者】 NOT【非】 来进行逻辑匹配。 就可以表达出一些复杂的条件。
-- 在查询时,可以指定 order by 子句进行结果的排序。
-- 有两个特殊的关键字 asc 【升序:默认】 、desc 【降序】
select * from `order` order by id -- 默认按升序排序
select * from `order` order by id DESC -- 按id降序排序
select * from `order` order by user asc,id desc -- 先按user升序排列,再按id降序排序
-- 计数 count()
select count(*) from `order` where amount>= 150 and amount<=550
select count(1) from `order` where amount>= 150 and amount<=550 【推荐】
-- 求和 sum()
-- 最大值 max()
-- 最小值 min()
-- 平均值 avg()
-- group by 用于按字段分组
-- 分组以后, select 后面只能出现跟分组有关的 那些列 及其聚合。
select amount, count(amount) from `order` group by amount
-- 分组过滤,不能使用普通认为的 where 条件来指定,应该使用 having 关键字
select amount, count(amount) from `order`
group by amount HAVING COUNT(amount)>1 --按amount进行分组,且过滤数量大于1的记录。
sql语句练习50题(Mysql版)
经典SQL练习题(MySQL版)