将之前学习的数据库知识在整理下,主要是看的**《SQL必知必会》**。这本书不愧是经典,入门数据库真的完全足够啦!
比如创建一个user
表,包含用户id、用户名、用户年纪等各种字段信息
create table user(
id int(10) unsigned not null auto_increment comment 'user_id', -- auto_increment自增,指定为主键
name varchar(20) not null comment "用户姓名",
age tinyint unsigned null comment "用户年纪",
email varchar(50) not null comment "用户邮箱",
fee decimal(10,2) not null default 0.00 comment "用户余额", -- 总长度是10位,保留2位有效小数位
create_time timestamp not null comment "注册时间",
primary key(id) -- 指定主键
);
NULL
表示没有值,空字符串是’’null
或者not null
NULL
的值不能作为主键primary key
和auto_increment
必须连在一起使用id
号进行插入。字段和值一一对应即可insert into user(name, email, age, fee, password)
values("xiaoming", "123456@qq.com", 20, 25.18, Password("xiaoming")); -- id号可以省略
笔记:
Password
insert into user values(3, "xiaoming", "123456@qq.com", 20, 25.18, Password("xiaoming")); -- id为3也不能省略
insert into user(name, --省略了age字段
email,
fee,
password)
values("xiaoming",
"123456@qq.com",
25.18,
Password("xiaoming"));
insert into user(name, email, age, fee, password)
select name, email, age, fee, password
from old_user; -- 从 old_user 中检索出数据插入 user 中
select * -- 可以指定某些字段,而不是全部
into new_user
from old_user; -- 将old_user中将数据全部复制到new_user中
alter table user
add phone char(20); --增加一个字段
alter table user
drop column phone; -- 删除表中的字段
永久性地删除某个表
drop table user;
alter table user rename to new_user;
通过关键字update和set来实现数据的更新
mysql> update user set name="nangying" where id=6; // 通过id指定
mysql> update user set fee=88.76 where fee=56.90; // 通过字段名直接指定
mysql> update user set email="81847919@qq.com", age=54 where id=7; // 同时修改多个值
mysql> update user set fee=88.88 where id in(2,4,6); // in的用法
mysql> update user set fee=66.66 where id between 2 and 6; // between ... and ...
删除表有两种情况:
delete
:删除表中的行,而不是表本身,插入数据从上一次结束
的id
号开始继续插入;占用内存truncate
:清空表,重新插入数据id
从1开始;不占内存空间delete table user;
truncate table user;
SQL中允许执行多个查询,即执行多条select语句,并将结果作为一个查询结果进行返回。两种情况需要使用组合查询:
在每条select语句之间放上关键字union
select name, contact, email
from customers
where state in ('IL', 'IN', 'MI')
union -- 通过关键字来连接两个子句
select name, contact, email
from customers
where name = 'Fun4All'
-- 通过多个where子句来实现上述功能
select name, contact, email
from customers
where state in ('IL', 'IN', 'MI')
or name = 'Fun4All' -- or是关键字
笔记:
union
至少由两条或者两条以上的select
语句构成使用一条order by
子句来进行排序,而且一定是最后的一行
select name, contact, email
from customers
where state in ('IL', 'IN', 'MI')
union -- 通过关键字来连接两个子句
select name, contact, email
from customers
where name = 'Fun4All'
order by name, contact -- 排序功能