001-MYSQL练习—创建+插入+更新+简单搜索

练习来源:https://blog.csdn.net/fuchunyuan0/article/details/51883889?locationNum=3&fps=1

1. 创建表的代码

if not exists——检查数据库中是否有该表,若是没有该表,则进行创建

/*创建顾客表*/
create table if not exists customer(
     c_id char(6) primary key,
     name varchar(30)not null,
     location varchar(30),
     salary decimal(8,2)

);
/*创建银行表*/
create table if not exists bank(
    b_id char(5) primary key,
    bank_name char(30) not null
);
/*创建存款表(注意外键的代码使用)*/
create table if not exists deposite(
    d_id int(10) auto_increment primary key,
    c_id char(6),
    b_id char(5),
    dep_date date,
    amount decimal(8,2),
    constraint FK_c_id foreign key(c_id) references customer(c_id)
);

2. 插入数据

/*插入数据*/
insert into customer 
values('101001','孙杨','广州',1234),
('101002','郭海','南京',3526),
('101003','卢江','苏州',6892),
('101004','郭惠','济南',3492),
('101005','张三','济南',4188),
('101006','李四','南京',7455);
/*插入银行数据*/
insert into bank
values('B0001','工商银行'),
('B0002','建设银行'),
('B0003','中国银行'),
('B0004','农业银行');
/*插入存款数据*/
insert into deposite
values(1,'101001','B0001','2011-04-05',42526),
(2,'101002','B0003','2012-07-15',66500),
(3,'101003','B0002','2010-11-24',42366),
(4,'101004','B0004','2008-03-31',62362),
(5,'101001','B0003','2002-02-07',56346),
(6,'101002','B0001','2004-09-23',353626),
(7,'101003','B0004','2003-12-14',36236),
(8,'101004','B0002','2007-04-21',26267),
(9,'101001','B0002','2011-02-11',435456),
(10,'101002','B0004','2012-05-13',234626),
(11,'101003','B0003','2001-01-24',26243),
(12,'101004','B0001','2009-08-23',45671),
(13,'101005','B0001','2011-04-09',252016),
(14,'101006','B0001','2010-07-16',12745),
(15,'101006','B0002','2009-05-31',37258),
(16,'101005','B0003','2008-12-17',274159),
(17,'101003','B0001','2008-09-14',10257);

2. 更新数据

例如:将孙杨名下的账户,金额都+1000

一开始的数据:

select * from deposite,customer,bank 
where deposite.c_id=customer.c_id 
and deposite.b_id=bank.b_id
and name='孙杨';

更新数据:

update  deposite 
set amount =amount+1000
 where c_id in(select c_id from customer where name='孙杨');
//因为deposite表中没有名字,所以用查询语句搜索出对应名字的ID作为条件,跟where语句结合起来

update 表名
set 字段=XXX
where 条件(XX字段=XX)
也可以写成搜索语句则为

where 字段 in (select XX from XX where XX=XX)

更新练习:
将张三的银行存款账户名称更改为建设银行

更新后:

update deposite 
set b_id=(select b_id from bank where bank_name='建设银行')
where c_id in(select c_id from customer where name='张三');

若是修改多个数据变成相同的,会出现问题,无法修改成功,或者后面出现问题

3、搜索

1、去重:DISTINCT——放在列的前面

——只返回不同的值

select distinct b_id from deposite;

注意: distinct 针对所有列,不能部分使用;所以除非两个列都不同,不然所有的数据都会被检索出来

例如下方情况:select distinct c_id, b_id from deposite;

2、限制返回值

limit——指定返回行

select * from deposite  limit 4;(返回deposite 表的前四行)

指定开始和结束行

select * from deposite limit 2,4;(第二行开始,实际显示是3、4、5、6,带出4行)

或者用select * from deposite limit 4 offset 2;

注:因为第一行为行0,所以limit 1,1将检索出第二行,以此类推

若只有13行,但是检索limit 10,5,则也只能返回最后2行

补充说明:

如果是想要清空表中的内容,使用delete字段

清空表内容:

delete from bank;

delete from bank where b_id=B0001;——删除某一行

猜你喜欢

转载自blog.csdn.net/cathyx88x/article/details/80318154