将一个key放到另外一个key之后: alter table Addressbook modify mail_address varchar(20) after tel_no;
删出一个表: DROP TABLE Product;
恢复一个表: ``
从表中选出固定的列: SELECT product_id, product_name, purchase_price FROM Product;
查询全部的列: SELECT * FROM <表名>;
为列设置列名: SELECT product_id AS id, product_name AS name, purchase_price AS price FROM Product;
设定汉语别名时需要使用双引号(")括起来。
distinct 删除重复的行: SELECT DISTINCT product_type FROM Product;
根据WHERE语句来选择记录: SELECT <列名>, …… FROM <表名> WHERE <条件表达式>
SELECT product_name, product_type FROM Product WHERE product_type = ‘衣服‘;
mysql 用 -- 进行单行注释,用/**/进行多行注释。
比较运算符: SELECT product_name, product_type FROM Product WHERE sale_price = 500;
where可以做减: SELECT product_name, sale_price, purchase_price FROM Product WHERE sale_price - purchase_price >= 500;
选取不为NULL的记录: SELECT product_name, purchase_price FROM Product WHERE purchase_price IS NOT NULL;
选取为NULL的记录:SELECT product_name, purchase_price FROM Product WHERE purchase_price IS NULL;
NOT运算符: 条件运算取非,SELECT product_name, product_type, sale_price FROM Product WHERE NOT sale_price >= 1000;
NOT运算符用来否定某一条件,但是不能滥用。
AND运算符和OR运算符: 可以对多个查询条件进行组合。
SELECT product_name, purchase_price FROM Product WHERE product_type = ‘厨房用具‘ AND sale_price >= 3000;
SELECT product_name, purchase_price, product_type FROM Product WHERE product_type = ‘厨房用具‘ or sale_price >= 3000;
多个查询条件进行组合时,需要使用AND运算符或者OR运算符。
SELECT product_name, product_type, regist_date FROM Product WHERE product_type = ‘办公用品‘ AND ( regist_date = ‘2009-09-11‘ OR regist_date = ‘2009-09-20‘);
聚合与排序
聚合函数:
COUNT: 计算表中的记录数(行数)
SUM: 计算表中数值列中数据的合计值
AVG: 计算表中数值列中数据的平均值
MAX: 求出表中任意列中数据的最大值
MIN: 求出表中任意列中数据的最小值
计算除 NULL 以外的行:SELECT COUNT(purchase_price) FROM Product;
INSERT INTO ProductType (product_type, sum_sale_price, sum_purchase_price) SELECT product_type, SUM(sale_price), SUM(purchase_price) FROM Product GROUP BY product_type;
向表中插入数据
数据删除:DELETE语句的使用方法
DROP TABLE语句和DELETE语句:
DROP TABLE 语句可以将表完全删除
DROP TABLE 语句会完全删除整张表,因此删除之后再想插入数据,就必须使用CREATE TABLE 语句重新创建一张表.
CREATE VIEW ProductJim (product_id, product_name, product_type, sale_price, purchase_price, regist_date) AS SELECT * FROM Product WHERE product_type = ‘办公用品‘;
INSERT INTO ProductJim VALUES (‘0009‘, ‘印章‘, ‘办公用品‘, 95, 10, ‘2009-11-30‘);
删除视图: DROP VIEW 视图名称(<视图列名1>, <视图列名2>, ……);
DROP VIEW ProductSum;
子查询: SELECT product_type, cnt_product FROM (SELECT Product_type, COUNT(*) AS cnt_product FROM Product GROUP BY product_type) AS ProductSum;
子查询作为内层查询会首先执行。
嵌套的子查询:
SELECT product_type, cnt_product
FROM (SELECT *
FROM (SELECT product_type, COUNT(*) AS cnt_product
FROM Product
GROUP BY product_type) AS ProductSum
WHERE cnt_product = 4) AS ProductSum2;
标量子查询就是返回单一值的子查询。
SELECT product_id, product_name, sale_price FROM Product WHERE sale_price > (SELECT AVG(sale_price) FROM Product);
SELECT product_id, product_name, sale_price, (SELECT AVG(sale_price) FROM Product) AS avg_price FROM Product;
SELECT product_type, AVG(sale_price) FROM Product GROUP BY product_type HAVING AVG(sale_price) > (SELECT AVG(sale_price) FROM Product);
标量子句只返回一个结果,该子查询绝对不能返回多行结果.
关联子查询会在细分的组内进行比较时使用。
关联子查询和GROUP BY子句一样,也可以对表中的数据进行切分。
关联子查询的结合条件如果未出现在子查询之中就会发生错误。
SELECT product_type, product_name, sale_price
FROM Product AS P1 WHERE sale_price > (SELECT AVG(sale_price)
FROM Product AS P2 WHERE P1.product_type = P2.product_type
GROUP BY product_type);
SELECT product_type, product_name, sale_price
FROM Product AS P1
WHERE P1.product_type = P2.product_type
AND sale_price > (SELECT AVG(sale_price)
FROM Product AS P2
GROUP BY product_type); --- 作用域不对
SELECT product_type, product_name, sale_price
FROM Product AS P1
WHERE sale_price>(SELECT AVG(sale_price)
FROM Product AS P2
WHERE P1.product_type=P2.product_type
GROUP BY product_type);
CREATE TABLE SampleStr
(str1 VARCHAR(40),
str2 VARCHAR(40),
str3 VARCHAR(40));
START TRANSACTION;
INSERT INTO SampleStr (str1, str2, str3) VALUES ('opx' , 'rt',NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('abc' , 'def' ,NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('山田' , '太郎' ,'是我');
INSERT INTO SampleStr (str1, str2, str3) VALUES ('aaa' , NULL ,NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES (NULL , 'xyz',NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('@!#$%' , NULL ,NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('ABC' , NULL ,NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('aBC' , NULL ,NULL);
INSERT INTO SampleStr (str1, str2, str3) VALUES ('abc太郎' , 'abc' ,'ABC');
INSERT INTO SampleStr (str1, str2, str3) VALUES ('abcdefabc' , 'abc' ,'ABC');
INSERT INTO SampleStr (str1, str2, str3) VALUES ('micmic' , 'i' ,'I');
COMMIT;
函数,谓词,case表达式
函数的种类:
算术函数(用来进行数值计算的函数)
ABS——绝对值
SELECT m, ABS(m) AS abs_col FROM SampleMath;
MOD——求余
SELECT n, p, MOD(n, p) AS mod_col FROM SampleMath;
ROUND——四舍五入
SELECT m, n, ROUND(m, n) AS round_col FROM SampleMath;
字符串函数(用来进行字符串操作的函数)
||——字符串拼接.
SELECT str1, str2, str1 || str2 AS str_concat FROM SampleStr;
MySQL使用CONCAT函数来完成字符串的拼接
SELECT str1, str2, str3, CONCAT(str1, str2, str3) AS str_concat FROM SampleStr;
LENGTH——字符串长度
SELECT str1, LENGTH(str1) AS len_str FROM SampleStr;
LOWER——小写转换
SELECT str1, LOWER(str1) AS low_str FROM SampleStr WHERE str1 IN (‘ABC‘, ‘aBC‘, ‘abc‘, ‘山田‘);
REPLACE——字符串的替换
SELECT str1, str2, str3, REPLACE(str1, str2, str3) AS rep_str FROM SampleStr;
REPLACE(对象字符串,替换前的字符串,替换后的字符串).
SUBSTRING——字符串的截取
SUBSTRING(对象字符串 FROM 截取的起始位置 FOR 截取的字符数)
SELECT str1, SUBSTRING(str1 FROM 3 FOR 2) AS sub_str FROM SampleStr;
日期函数(用来进行日期操作的函数)
CURRENT_DATE——当前日期
select CURRENT_DATE;
CURRENT_TIME——当前时间
select CURRENT_TIME;
CURRENT_TIMESTAMP——当前日期和时间
select CURRENT_TIMESTAMP;
EXTRACT——截取日期元素
SELECT CURRENT_TIMESTAMP, EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AS year, EXTRACT(MONTH FROM CURRENT_TIMESTAMP) AS month, EXTRACT(DAY FROM CURRENT_TIMESTAMP) AS day, EXTRACT(HOUR FROM CURRENT_TIMESTAMP) AS hour, EXTRACT(MINUTE FROM CURRENT_TIMESTAMP) AS minute, EXTRACT(SECOND FROM CURRENT_TIMESTAMP) AS second;
转换函数(用来转换数据类型和值的函数)
CAST——类型转换
CAST(转换前的值 AS 想要转换的数据类型)
COALESCE——将NULL转换为其他值
COALESCE(数据1,数据2,数据3……)
SELECT COALESCE(NULL, 1) AS col_1, COALESCE(NULL, ‘test‘, NULL) AS col_2, COALESCE(NULL, NULL, ‘2009-11-01‘) AS col_3;
聚合函数(用来进行数据聚合的函数)
聚合函数基本上只包含COUNT、SUM、AVG、MAX、MIN
谓词:
LIKE
字符串的部分一致查询
SELECT * FROM SampleLike WHERE strcol LIKE ‘ddd%‘;
SELECT * FROM SampleLike WHERE strcol LIKE ‘%ddd%‘;
SELECT * FROM SampleLike WHERE strcol LIKE ‘%ddd‘;
使用LIKE和_(下划线)进行后方一致查询
SELECT * FROM SampleLike WHERE strcol LIKE ‘abc__‘;
BETWEEN
BETWEEN谓词——范围查询
SELECT product_name, sale_price FROM Product WHERE sale_price BETWEEN 100 AND 1000;
IS NULL、IS NOT NULL
IS NULL、IS NOT NULL——判断是否为NULL
SELECT product_name, purchase_price FROM Product WHERE purchase_price IS NULL;
SELECT product_name, purchase_price FROM Product WHERE purchase_price IS NOT NULL;
IN
IN谓词——OR的简便用法
SELECT product_name, purchase_price FROM Product WHERE purchase_price IN (320, 500, 5000);
SELECT product_name, sale_price FROM Product WHERE product_id NOT IN (SELECT product_id FROM ShopProduct WHERE shop_id = ‘000A‘);
EXISTS
谓词的作用就是“判断是否存在满足某种条件的记录”。
SELECT product_name, sale_price FROM Product AS P WHERE EXISTS (SELECT * FROM ShopProduct AS SP WHERE SP.shop_id = ‘000C‘ AND SP.product_id = P.product_id);
通常指定关联子查询作为EXIST的参数。
CASE表达式:
CASE 表达式也是函数的一种
CASE 表达式是在区分情况时使用的,这种情况的区分在编程中通常称为(条件)分支
CASE表达式的语法分为简单CASE表达式和搜索CASE表达式两种.
CASE WHEN <求值表达式> THEN <表达式>
WHEN <求值表达式> THEN <表达式>
WHEN <求值表达式> THEN <表达式>
.. .
ELSE <表达式>
END
SELECT product_name, CASE WHEN product_type = ‘衣服‘ THEN CONCAT(‘A :‘, product_type) WHEN product_type = ‘办公用品‘ THEN CONCAT(‘B :‘, product_type) WHEN product_type = ‘厨房用具‘ THEN CONCAT(‘C :‘, product_type) ELSE NULL END AS abc_product_type FROM Product;
SELECT SUM(CASE WHEN product_type = ‘衣服‘ THEN sale_price ELSE 0 END) AS sum_price_clothes, SUM(CASE WHEN product_type = ‘厨房用具‘ THEN sale_price ELSE 0 END) AS sum_price_kitchen, SUM(CASE WHEN product_type = ‘办公用品‘ THEN sale_price ELSE 0 END) AS sum_price_office FROM Product;
简单CASE表达式
CASE <表达式>
WHEN <表达式> THEN <表达式>
WHEN <表达式> THEN <表达式>
WHEN <表达式> THEN <表达式>
.. .
ELSE <表达式>
END
SQL 高级处理
窗口函数
窗口函数也称为OLAP 函数.
<窗口函数> OVER ([PARTITION BY <列清单>] ORDER BY <排序用列清单>)
RANK、DENSE_RANK、ROW_NUMBER 等专用窗口函数
窗口函数兼具分组和排序两种功能。
SELECT product_name, product_type, sale_price, RANK () OVER (PARTITION BY product_type ORDER BY sale_price) AS ranking FROM Product;
通过PARTITION BY分组后的记录集合称为“窗口”
SELECT product_name, product_type, sale_price, RANK () OVER (ORDER BY sale_price) AS ranking FROM Product; --- 全部商品进行排序。
RANK函数 --- 计算排序时,如果存在相同位次的记录,则会跳过之后的位次。
DENSE_RANK函数 --- 同样是计算排序,即使存在相同位次的记录,也不会跳过之后的位次。
ROW_NUMBER函数 --- 赋予唯一的连续位次。
SELECT product_id, product_name, sale_price, AVG (sale_price) OVER (ORDER BY product_id ROWS 2 PRECEDING) AS moving_avg FROM Product; --- 计算移动平均数。
GROUPING运算符 --- 得到合计行
SELECT ‘合计‘ AS product_type, SUM(sale_price) FROM Product UNION ALL SELECT product_type, SUM(sale_price) FROM Product GROUP BY product_type; --- 得到合计行
ROLLUP——同时得出合计和小计:
GROUPING 运算符包含以下3 种:
ROLLUP
SELECT product_type, SUM(sale_price) AS sum_price FROM Product GROUP
BY product_type WITH ROLLUP;