MySQL入门-聚合函数/连接查询/子查询

使用聚合函数

COUNT(),SUM(),AVG(),MAX(),MIN()

SELECT COUNT(*) AS total FROM sheet1$;
SELECT TYPE,COUNT(*) AS total FROM sheet1$ GROUP BY TYPE;
SELECT response,SUM(charge) FROM sheet1$ WHERE response = '小小黑子';
SELECT response,SUM(charge) FROM sheet1$ GROUP BY response;
SELECT response,AVG(charge) FROM sheet1$ GROUP BY response;
SELECT response,MAX(charge) FROM sheet1$ WHERE response= '小小黑子';
SELECT response,MAX(charge) FROM sheet1$ GROUP BY response;

SELECT response,MIN(charge) FROM sheet1$ GROUP BY response;

连接查询
SELECT * FROM sheet1$,sheet2$;-- 笛卡尔乘积,返回22*22=484行
SELECT * FROM sheet1$,sheet2$ WHERE sheet1$.`name` = sheet2$.`name`;-- 查询表1和表2中name相等的行
SELECT sh2.charge,sh1.name,sh1.num FROM sheet1$ AS sh1,sheet2$ AS sh2 WHERE sh1.`name` = sh2.`name`;
SELECT * FROM sheet1$ LEFT JOIN sheet2$ ON sheet1$.`response` = sheet2$.`response`;-- 左连接,能查出表1所有数据,表二response及之后的数据
SELECT * FROM sheet1$ RIGHT JOIN sheet2$ ON sheet1$.`response` = sheet2$.`response`;
SELECT sh2.charge,sh1.name,sh1.num FROM sheet1$ AS sh1,sheet2$ AS sh2 WHERE sh1.`name` = sh2.`name` AND sh2.`value`>80000;

子查询

SELECT * FROM sheet1$ WHERE response NOT IN (SELECT response FROM sheet2$);-- 带in 关键字的子查询
SELECT * FROM sheet1$ WHERE num>=(SELECT num FROM sheet2$ WHERE id2=1);-- 带比较的子查询
SELECT * FROM sheet1$ WHERE NOT EXISTS (SELECT * FROM sheet2$);-- 带EXISTS关键字查询
SELECT * FROM sheet1$ WHERE charge >= ANY (SELECT VALUE FROM sheet2$); -- 满足任一条件
SELECT * FROM sheet1$ WHERE charge >= ALL (SELECT charge FROM sheet2$);-- 满足所有条件查询

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