mysql学习|青训营笔记

63 阅读3分钟

这是我参加[第四届青训营]笔记创作活动的第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_idfirst_namepointstype
:-:---------------------------------
 4Ambur457Bronze
 1Babara2273Silver
 5Clemmie3675Gold
 6Elka3073Gold
 3Freddi2967Silver
 7Ilene1672Bronze
 2Ines947Bronze
 10Levy796Bronze
 9Romola1486Bronze
 8Thacher205Bronze

第三章

image.png 如图,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不为空)

image.png

做法:

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

结果:

203-898-6735Topiclounge175.328.182019-06-112019-07-012019-02-12
675-587-6626Vinte157.7874.552019-01-292019-02-182019-01-03
1120-848-0181Yadel126.150.032019-01-072019-01-272019-01-11
1341-666-1035Topiclounge135.0187.442019-06-252019-07-152019-01-26
1555-105-9605Yadel167.2980.312019-11-252019-12-152019-01-15
1733-615-4694Yadel126.3868.102019-07-302019-08-192019-01-15
1852-269-9803Topiclounge180.1742.772019-05-232019-06-122019-01-08
------
今天的学习就到这里吧。