这是我参加[第四届青训营]笔记创作活动的第10天。
第一部分:
交叉连接
-- 交叉连接
use sql_store;
select
c.first_name as customer,
p.name as product
from customers c
cross join products p
order by c.first_name
-- 类似与笛卡尔积的效果
-- from customers c,orders o 就是隐式的写法
联合:
我们前面学习的都是列与列之间的联合,其实行与行之间也可以进行联合,下面我们来看一下具体的方法。
use sql_store;
select
order_id,
order_date,
'Active' as status
from orders
where order_date >= '2019-01-01'
union
select
order_id,
order_date,
'Archived' as status
from orders
where order_date < '2019-01-01'
具体实例:
要求根据顾客的积分给顾客打上标签。 代码:
-- 联合,不同行之间的结合。
use sql_store;
select
customer_id,
first_name,
points,
'Bronze' as type
from customers
where points < 2000
union
select
customer_id,
first_name,
points,
'Silver' as type
from customers
where points between 2000 and 3000
union
select
customer_id,
first_name,
points,
'Gold' as type
from customers
where points > 3000
order by first_name
关于2000-3000之间为什么使用between and 我也不清楚为什么,只是如果写2000<points<3000会出现重复行,与设想的结果不一样。一般的编程语言好像都不可以。
结果:
| 标题 | |||||
|---|---|---|---|---|---|
| customer_id | first_name | points | type | ||
| :-: | ----------- | ---------- | ------ | ------ | |
| 4 | Ambur | 457 | Bronze | ||
| 1 | Babara | 2273 | Silver | ||
| 5 | Clemmie | 3675 | Gold | ||
| 6 | Elka | 3073 | Gold | ||
| 3 | Freddi | 2967 | Silver | ||
| 7 | Ilene | 1672 | Bronze | ||
| 2 | Ines | 947 | Bronze | ||
| 10 | Levy | 796 | Bronze | ||
| 9 | Romola | 1486 | Bronze | ||
| 8 | Thacher | 205 | Bronze |
第三章
如图,pk代表是不是主值,主值可以唯一代表一组数据。nn代表不可以为空值。ai代表主动递增。
default代表默认值。
学会对列的插入等操作,其实就是普通的excel的操作,不过excel的操作是不是更加直观,就像是可视化等等。
插入多行
/*insert into products(
product_id,
name,
quantity_in_stock,
unit_price)
values(
default,
'aaa',
12,
2.09),
(
default,
'aba',
14,
2.096)*/
注意,/* */是mysql的多行注释。
插入分成行: 显然没听懂,看下一节好啦。
创建表复制
-- 创建复制表格
-- create table orders_archived as
-- select * from orders
-- 可以用insert into复制一部分到新的表格里面
/*insert into orders_archived
select *
from orders
where order_date < '2019-01-01'*/
例题: 将表格中的clients换成顾客的名字,将有发票的人都筛选出来(payment_date不为空)
做法:
use sql_invoicing;
create table inv_archived as
select
invoice_id,
number,
name,
invoice_total,
payment_total,
invoice_date,
due_date,
payment_date
from invoices inv
left join clients c
on inv.client_id = c.client_id
where inv.payment_date is not null
结果:
| 2 | 03-898-6735 | Topiclounge | 175.32 | 8.18 | 2019-06-11 | 2019-07-01 | 2019-02-12 | |
|---|---|---|---|---|---|---|---|---|
| 6 | 75-587-6626 | Vinte | 157.78 | 74.55 | 2019-01-29 | 2019-02-18 | 2019-01-03 | |
| 11 | 20-848-0181 | Yadel | 126.15 | 0.03 | 2019-01-07 | 2019-01-27 | 2019-01-11 | |
| 13 | 41-666-1035 | Topiclounge | 135.01 | 87.44 | 2019-06-25 | 2019-07-15 | 2019-01-26 | |
| 15 | 55-105-9605 | Yadel | 167.29 | 80.31 | 2019-11-25 | 2019-12-15 | 2019-01-15 | |
| 17 | 33-615-4694 | Yadel | 126.38 | 68.10 | 2019-07-30 | 2019-08-19 | 2019-01-15 | |
| 18 | 52-269-9803 | Topiclounge | 180.17 | 42.77 | 2019-05-23 | 2019-06-12 | 2019-01-08 | |
| --- | --- | |||||||
| 今天的学习就到这里吧。 |