数据库基础.数据库查询及约束【作业】


一、前言

这道题目还是考察了一下对数据库的基本操作是否熟练


二、题目:根据信息创建对应的表单

已知:商品信息表

表名为:Goods,包含ID(自增主键)、NAME(名称、惟一性约束)、Price(价格)、trademark(品牌)和Type(类型,默认值为‘手机’)字段。

表单信息

(1).写出建表语句
(2). 查询价格在2000以下的商品名称和剩余数量

(3). 统计各个类别下的商品数量

(4). 按价格排序输出全部商品

(5). 统计各个类别下的最低商品价格

(6). 查询Samsung品牌下的所有商品

(7). 查询价格最高的前3个商品信息

(8). 查询Apple品牌下的商品类别总数

(9). 写出SQL语句,向表中插入一条记录

(10). 写出SQL语句,修改编号为510093的商品数量为5

(11).写出sql语句,删除数量为0的商品

三、遇到的BUG:

1.自增语句无法使用

我们看到题目要求写出自增语句,对ID进行自增操作,所以我们上网搜寻了一下,找到identity(1,1)是可以作为自增语句来使用的。

Create table Goods (
	ID int primary key identity(1,1), 
	NAME char(30),
	Price int,
	trademark char(30),
	Type char(30) default '手机' );

ID primary key identity(1,1);

我们将上述程序在数据库里操作之后,出现以下情况:
程序出现BUG

为什么identity(1,1)不能用在这里?

identity不能用于MySQL的原因:

  • 原因是MySQL没有identity函数,在MySQL中设置自动编号是需要用auto_increment的。
create table student(
	id int primary key auto_increment,
	name varchar(20)
)

#设置自增的初值
AUTO_INCREMENT=<你期望的起始id值>
ALTER TABLE <表名> AUTO_INCREMENT=<你期望的起始id值>
#eg:
alter table student auto_increment = 100;

四、答案仅供参考

1.创建表格

//建表
create table Goods (
ID int auto_increment primary key not null, 
NAME char(30),
Price int ,
CNT int ,
trademark char(30),
Type char(30) default '手机' );

//设置自增初值
alter table goods auto_increment = 51091;

insert into goods (NAME,Price,CNT,trademark,Type) value('MacBook Air MD224',8799,30,'Apple','笔记本');
insert into goods (NAME,Price,CNT,trademark,Type) value('Galaxy Note II N7100',5199,100,'Samsung','手机');
insert into goods (NAME,Price,CNT,trademark,Type) value('MV800',1499,200,'Samsung','相机');
insert into goods (NAME,Price,CNT,trademark,Type) value('K860 四核 3G',2188,300,'Lenovo','手机');
insert into goods (NAME,Price,CNT,trademark,Type) value('S7562 3G',1798,200,'Samsung','手机');
insert into goods (NAME,Price,CNT,trademark,Type) value('Y470P-IFI',4299,200,'Lenovo','笔记本');
insert into goods (NAME,Price,CNT,trademark,Type) value('NP-E3415-J01CN',3300,150,'Samsung','笔记本');
insert into goods (NAME,Price,CNT,trademark,Type) value('iPhone 4S 64G',4799,220,'Apple','手机');

此时表格已经创建完毕:

出

2.剩余的题目

#第二题(2). 查询价格在2000以下的商品名称和剩余数量
select NAME,CNT,Price from goods where price < 2000;

#第三题(3). 统计各个类别下的商品数量
select type,sum(cnt) SumType from goods group by type;

#(4). 按价格排序输出全部商品
select ID, name,price, trademark from goods order by price asc;

#(5). 统计各个类别下的最低商品价格
select type, min(price) minPriceofType from goods group by type;

#(6). 查询Samsung品牌下的所有商品
select ID,name from goods where trademark = 'Samsung';

#(7). 查询价格最高的前3个商品信息
select id, name, price, cnt, type from goods
order by price desc limit 0,3;

#(8). 查询Apple品牌下的商品类别总数
select type, count(ID) from goods where trademark = 'Apple' group by type;

#(9). 写出SQL语句,向表中插入一条记录
insert into goods value(5555,'Legin_Y7000',6999,1,'lenove','笔记本');

#(10). 写出SQL语句,修改编号为51093的商品数量为5
update goods set cnt = 5 where id = 51093;

#(11).写出sql语句,删除数量为0的商品
delete from goods where cnt = 0;

执行完所有程序之后:

表格创建完毕!

猜你喜欢

转载自blog.csdn.net/weixin_43801418/article/details/110848103