SQL笔记——表的操作、数据修改、列的属性和查询操作
表的操作
在之前应该有一个数据库
(图片来源网络,侵删)
先创建一个 user 库,然后可以查看、修改、删除
create databases user;//创建 show databases; //展示 alter databases user //修改 修改的内容; drop databases user1;//删除 或者是 drop databases if exists user1;
添加数据之前肯定要知道你要添加什么数据 类型怎么定义,接下来是列的属性
列的属性
default 默认值 not null 非空 auto_increment 自增 check 条件检查 unique 唯一值 primary key 主键 唯一性不为空 foregin key 外键 comment 注释 create table a{ id int auto_increment unique comment '索引', --开始是1 每次增加 name varchar(10) not null, city varchar(10) comment '城市', age int default 10, weight int check(weight in(50,23,26,28,24) rdata date }; --如果想删除这些设置,可以用 alter table a add(drop) constraint 内容; alter table a drop constraint unique(id); alter table a add constraint primary key(id);
创建表和修改表的操作
记住有库后才有表,在数据库user下创建一个名字叫a的表,如下
表中的字段包括了 id、name等等用逗号隔开,!最后一句没有逗号!
use user; create table a{ id int, name varchar(10), city varchar(10), rdata date }; -- 查看表 show tables; describe 表名; -- 展示a表 describe a; -- 删除表 drop table a; ---- 修改表 --修改a名字为a1 alter table a rename to a1; -- 添加字段 alter table 表名 add 列名 数据类型; add weight int; -- 删除字段 alter table 表名字 drop 列名; -- 修改列名字 alter table a change weight w int; -- 修改数据类型 alter table a modify w char(4);
其实很好记就是
alter table 表名+操作(add、drop、change、modify)等等
复制a1表名字为a2,此时只是表结构一致,数据还没有复制过来
create table a2 like a1;
复制数据的操作,这时候a3跟a1 结构和数据一模一样 (假设有数据了哈)
create table a3 as(select * from a1);
有了数据库,也有表了,那就的添加数据了
终于可以添加数据了
数据修改
insert语句
记得加入的内容和表的字段顺序一致哈!!
方式1 insert into a(id,name,city,rdate) values(1,cici,'广州','2025-1-2'), (2,xixi,'广西','2020-10-6'), (6,hh,'重庆','2023-11-6'); 方式2 insert into a values(1,cici,'广州','2025-1-2'), (2,xixi,'广西','2020-10-6'), (6,hh,'重庆','2023-11-6'); -- 插入部分 insert into a(id,rdate) values(8,'2021-1-2');
如果数据中已经存在你想插入的,需要用replace覆盖原来的
replace 语句
replace into a(id,name,city,rdate) values(6,hh,'重庆','2023-11-6');
udpdate
update a set age=40: update a set age=40 where name='cici'; update a set age=40, city='广西' where name='cici';
delete
delete from a where id=5; delete from a where id in (1,5,2);
truncate table a 也可以删除 但是把所有的删除
查询操作
select 语句
select * from a; select id from a; select id,city from a; select '特殊名字' from a; 也就是说特殊名字 如名字中间带空格的,应该加引号使用
as语句 ------别名设计**
select name as aname from a; -- 英文别名 select name as 名字 from a;-- 中文名字 select name as 名字, city as 城市 from a; select name as "特殊名字" from a;
也就是说特殊名字 如名字中间带空格的,应该加 双 引号使用
where 语句
语句格式
select * from a where id=4; select * from a where name='小米'; select * from a where age>20;
and or not语句
运算顺序not >and >or
select * from a where id>5 and id5 or id>=10; select * from a where not id
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。