柚子酱的Mysql学习笔记(二)

聚集函数

柚子酱的Mysql学习笔记(二)_第1张图片
1.AVG函数

SELECT AVG(col_name1) AS avg_col
FROM table_name;

返回特定行的平均值

SELECT AVG(col_name) AS avg_col
FROM table_name
WHERE condition;

2.COUNT()函数
确定表中行的数目或满足特定条件的行的数目,忽略NULL值

SELECT COUNT(*) AS num_col
FROM table_name;

其余函数不再赘述,使用方法相同

3.聚集不同的值
若有些行的值相同,不再重复计算,使用DISTINCT参数

SELECT AVG(DISTINCT col_name) AS avg_col
FROM table_name
WHERE condition

4.组合聚集函数

SELECT COUNT(*) AS num_col,
		MIN(col_name) AS min_col,
		MAX(col_name) AS max_col,
		AVG(col_name) AS avg_col
FROM table_name;

分组函数

将数据分为多个逻辑组
1.创建分组

SELECT col_name1, COUNT(*) AS num_col
FROM table_name
GROUP BY col_name1;

GROUP BY子句必须出现在WHERE子句之后,ORDER BY子句之前。

2.过滤分组
过滤分组用来决定包括哪些分组,排除哪些分组,对分组进行条件限定

SELECT col_name1, COUNT(*) AS num_col
FROM table_name
GROUP BY col_name1
HAVING COUNT(*) >= 2;

3.分组间排序

SELECT col_name1, SUM(col_name2) AS sum_col
FROM table_name
GROUP BY col_name1
HAVING SUM(col_name2) >= 50
ORDER BY sum_col;

4.关键字顺序
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT

子查询

1.将多个查询组合起来

SELECT cust_id
FROM orders
WHERE ord_num IN (SELECT order_num
	          FROM orderitems
		  WHERE prod_id = 'TNT2');

选择购买了TNT2的顾客id
进一步查询这些顾客的姓名和联系方式

SELECT cust_name, cust_contact
FROM customers
WHERE cust_id IN (SELECT cust_id
		  FROM orders
		  WHERE ord_num IN (SELECT order_num
				    FROM orderitems
				    WHERE prod_id = 'TNT2'));

2.内部联结
联结条件用特定的ON子句而不是WHERE子句给出

SELECT col_name1, col_name2, col_name3
FROM table_name1 INNER JOIN table_name2
ON table_name1.col_name4 = table_name2.col_name5

3.使用表别名

SELECT col_name1, col_name2
FROM table_name1 AS A, table_name2 AS B
WHERE condition 

使用表别名可以方便自联结

4.外部联结
包含那些没有关联行的行
使用LEFT/RIGHT OUTER JOIN

SELECT customers.cust_id, orders.order_num
FROM customers LEFT OUTER JOIN orders
WHERE customers.cust_id = orders.cust_id

检索所有客户,包括没有订单的用户

组合查询

1.组合多个查询
在多个查询之间使用UNION

SELECT col_name1, col_name1
FROM table_name
WHERE condition1
UNION
SELECT col_name1, col_name2
FROM table_name
WHERE condition2

2.包含或者取消重复的行
UNION ALL包含所有重复的行
UNION 默认自动去除重复的行

3.查询结构排序
在使用UNION组合查询时,只能用一个ORDER BY语句
必须出现在最后一条SELECT语句之后

插入数据

1.插入完整的行

INSERT INTO table_name
VALUES(value1, value2, value3)

INSERT语句一般不会产生输出
或者指定列名,可以按任意次序

SELECT INTO table_name(col_name1, col_name2, col_name3)
VALUE(value1, value2, value3)

INSERT语句可能很好使,可以使用关键字LOW_PRIORITY 降低INSERT语句的优先级
INSERT LOW_PRIORITY INTO

2.插入多行值

INSERT INTO table_name
VALUES(value1, value2, value3),
     (value3, value4, value5);

更新与删除数据

1.更新数据

UPDATE table_name
SET col_name1 = new_value1,
    col_name2 = new_value2
WHERE condition;

为了删除某个列的值,可以设置它为NULL

2.删除数据

DELETE FROM table_name
WHERE condition;

小心使用DELETE语句,删库跑路!

你可能感兴趣的:(数据库)