这是我参加[第四届青训营]笔记创作活动的第11天。
今天又是愉快的学习mysql的一天,真高兴呀,,,,
更新多行
/*update invoices
set
payment_total = invoice_total * 0.5,
payment_date = due_date
where client_id = 3*/
在update中使用子查询
/*update invoices
set
payment_total = invoice_total * 0.5,
payment_date = due_date
where client_id in
(select client_id
from clients
where state in ('CA','NY'))*/
这里用 in,是因为返回来的数据不是一个。
删除行
/*delete from invoices
where ~*/
下面就是第五章了。据说十分有用。 聚合函数
-- 聚合函数
/*select
max(invoice_total) as highest,
min(invoice_total) as lowest,
avg(invoice_total) as average,
sum(invoice_total*1.1) as total,
count(distinct client_id) as total_records-- 只数非空的数值
-- distinct排除重复的数
from invoices*/
具体的例题: 要求根据发票表单查询下面的结果:
代码:
-- 聚合函数
select
'First half of 2019' as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as total_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
where invoice_date
between '2019-01-01' and '2019-06-30'
union
select
'Second half of 2019' as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as total_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
where invoice_date
between '2019-01-01' and '2019-12-30'
union
select
'Total' as date_range,
sum(invoice_total) as total_sales,
sum(payment_total) as total_payments,
sum(invoice_total-payment_total) as what_we_expect
from invoices
结果:
| First half of 2019 | 1539.07 | 611.79 | 927.28 | |
|---|---|---|---|---|
| Second half of 2019 | 2590.60 | 892.81 | 1697.79 | |
| Total | 2590.60 | 892.81 | 1697.79 | |
| --- | --- | |||
| 只能说大差不差。哈哈哈哈哈 |
分组:
-- 分组
select
state,
city,
sum(invoice_total) as total_sales
from invoices i
join clients using(client_id)
group by state,city
一、数据库简述
简单的说,数据库就是一个存放数据的仓库,这个仓库是按照一定的数据结构(数据结构是指数据的组织形式或数据之间的联系)来组织、存储的,我们可以通过数据库提供的多种方法来管理数据库里的数据。更简单的形象理解,数据库和我们生活中存放杂物的仓库性质一样,区别只是存放的东西不同。
2.1、SQL的优点
1、简单易学,具有很强的操作性
2、绝大多数重要的数据库管理系统均支持SQL
3、高度非过程化;用SQL操作数据库时大部分的工作由DBMS自动完成