第4章练习题-SQL基础教程

4.1 A先生在自己的计算机(电脑)上,使用 CREATE TABLE 语句创建出了
一张空的 Product(商品)表,并执行了如下的 SQL 语句向其中插入数据

start transaction;
    insert into product
    values
    ('0001', 'T恤', '衣服', 1000, 500, '2009-09-20'),
    ('0002', '打孔器', '办公用品', 500, 320, '2009-09-11'),
    ('0003', '运动T恤', '衣服', 4000, 2800, null);

紧接着,B 先生使用其他的计算机连接上该数据库,执行了如下 SELECT
语句。这时 B 先生能得到怎样的查询结果呢

select *
from product;

提示:如果可以使用DELETE语句,就可以对通过CREATE TABLE语句创建出
的空表执行该操作了

1 行也选取不出来

-- 正确的SQL语句如下
start transaction;
    insert into product
    values
    ('0001', 'T恤', '衣服', 1000, 500, '2009-09-20'),
    ('0002', '打孔器', '办公用品', 500, 320, '2009-09-11'),
    ('0003', '运动T恤', '衣服', 4000, 2800, null);
commit;

4.2 如下所示,有一张包含 3 条记录的 Product 表
第4章练习题-SQL基础教程_第1张图片
使用如下的 INSERT 语句复制这 3 行数据,应该就能够将表中的数据增加为 6 行。请说出该语句的执行结果

insert into product
select *
from product;

因为商品编号列违反了主键约束,所以会发生错误,1 行也插入不了

4.3 以练习 4.2 中的 Product 表为基础,再创建另外一张包含利润列的新表
ProductMargin(商品利润)

create table product_margin(
	product_id char(4) primary key not null,
	product_name varchar(100) not null,
	sale_price int,
	purchase_price int,
	margin int
);

请写出向上述表中插入如下数据的 SQL 语句,其中的利润可以简单地通过
对 Product 表中的数据进行计算(销售单价 - 进货单价)得出

第4章练习题-SQL基础教程_第2张图片

insert into product_margin
(product_id,product_name,sale_price,purchase_price,margin)
	select product_id,product_name,sale_price,purchase_price,sale_price - purchase_price
    from product;

4.4 对练习 4.3 中的 ProductMargin 表的数据进行如下更改:1. 将运动 T 恤的销售单价从 4000 日元下调至 3000 日元;2. 根据上述结果再次计算运动 T 恤的利润。更改后的ProductMargin表如下所示。请写出能够实现该变更的SQL语句
第4章练习题-SQL基础教程_第3张图片

update product_margin
set sale_price = 3000
where product_name = '运动T恤';

update product_margin
set margin = sale_price - purchase_price
where product_name = '运动T恤';

你可能感兴趣的:(SQL基础教程)