第三章 13-联合unions--Mosh mySQL

join:连接表,结合多张表(可以是不同张表也可以是同一张)的:union,union适用于查询多个结果。union之后的列名跟第一个查询的列名是一样的,如果需要更改,则调换顺序;如果需要重命名,则用as,比如select first_name as full_name.

1,在每个订单边添加一个标签,今年的订单active,之前的arichive

use sql_store;
select
order_id,
order_date,
'Active' as status
from orders
where order_date >='2019-01-01'

select
order_id,
order_date,
'Archived' as status
from orders
where order_date <'2019-01-01'

2,两端代码之间加上union,则结果相加

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'

3,不同的表的union。以下例子,从数据库中可以看到客户信息一共10人,发货一共5人,因此结果是10行。

select first_name
from customers
union
select name
from shippers

4,查询返回的列的数量要一样,否则会得到错误提示,如Error Code: 1222. The used SELECT statements have a different number of columns

举例:

select first_name ,last_name
from customers
union
select name
from shippers

练习

points<=2000,Bronze

2000<points<=3000,Silver

points>3000,Gold

答案:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值