Oracle 的SQL 语句练习 --- 建表,设置主外键,唯一、检查,非空约束,select查询

问:针对客户的需求:为客户设计表结构

1参照如下的说明设计出数据库结构
2你现在要为送水公司设计管理系统
3公司里有多少个送水工,他们的工资是这样计算的:底薪+(送水总数*每桶的提层比例)
4每个送水工的每桶提成比例不一样
5客户只有事先定了水票才能要求送水工送水
6送水工送了多少桶水就会从客户那里得到多少张水票

原则:先找到实体(主表),然后再找实体之间的关系(从表)

drop table history;
drop table worker;
drop table customer;
-- 客户表
create table customer(
id number(11),
cust_name varchar2(30) not null,  -- 客户姓名
cust_address varchar2(30) not null, -- 客户地址
cust_mobile varchar2(30) , -- 客户联系方式
cust_tickets number(5) not null     -- 客户持有的水票数量
);
-- 送水工表
create table worker(
id number(11),
worker_name varchar2(30) not null, 
worker_salary number(5) not null, -- 底薪
worker_ticheng number(2,1) not null , -- 每桶水的提成,长度一共两位 其中小数占据一位    
worker_image varchar(100)  -- 送水工的照片    
);

-- 送水历史表
create table history(
id number(11),
cust_id number(11) not null, -- 客户id
worker_id number(11) not null, -- 送水工id
send_water_time date not null,-- 送水工为客户送水的时间
send_water_count number(5) not null     -- 送水工为客户送水的数量
);

-- 为customer表创建主键约束
alter table customer add constraint pk_customer_id primary key(id);

-- 为customer表的cust_mobile 建立唯一约束
alter table customer add constraint un_customer_mobile unique(cust_mobile);

-- 为customer表的cust_ticket建立检查约束 水票不能为负数
alter table customer add constraint chk_customer_tickets check(cust_tickets>=0);

-- 为worker建立主键约束
alter table worker add constraint pk_worker_id primary key(id);

-- 为history表建立主键约束
alter table history add constraint pk_history_id primary key(id);

-- 为history表的cust_id建立外键,去关联customer表的主键
alter table history add constraint fk_history_cust_id foreign key(cust_id) references customer(id);

-- 为history表的worker_id建立外键,去关联worker表的主键
alter table history add constraint fk_history_worker_id foreign key(worker_id) references worker(id);

-- 为history表的send_water_count建立检查约束 送水数量不能为负数
alter table history add constraint chk_history_send_water_time check(send_water_count>=0);

-- 为customer表插入数据
insert into customer values(1,'Tom','Wuhan','15898763456',100);

-- 为worker表插入数据
insert into worker(id,worker_name,worker_salary,worker_ticheng)values(1,'Martin',1000,1.5);

-- 为从表history插入数据
-- 转换函数to_date('日期','日期格式') 将字符串转换为日期
insert into history values(1,1,1,to_date('2019-08-11','YYYY-MM-DD'),5);

commit;

-- 查看CUSTOMER客户表
select ID ,
CUST_NAME ,
CUST_ADDRESS ,
CUST_MOBILE ,
CUST_TICKETS  from CUSTOMER;

-- 查看WORKER送水工表
select ID ,
WORKER_NAME ,
WORKER_SALARY ,
WORKER_TICHENG ,
WORKER_IMAGE  from WORKER;

-- 查看history历史送水表
select ID ,
CUST_ID ,
WORKER_ID ,
to_char(send_water_time,'YYYY-MM-DD')送水日期 ,
SEND_WATER_COUNT  from HISTORY;
  • 日期
  • to_char(日期,‘格式’) 将日期转换为字符串
    select to_char(send_water_time,‘YYYY-MM-DD’) 送水日期 from history;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

樂小伍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值