最近笔试题目,总是碰到一些SQL语句的基本操作,现简单总结下。
题目:表名为t,name字段代表姓名,score字段代表分数,请根据要求写出SQL语句。
建表:
我使用的是navicat for MySQL 11.1.11.
代码:
5个问题代码写在一起了。第一行是先看看所有信息。
图片展示:
链式写法:
SELECT * FROM t;
SELECT name,SUM(score) FROM t GROUP BY name ORDER BY SUM(score) DESC LIMIT 1,4;
SELECT name,SUM(score) FROM t GROUP BY name HAVING SUM(score) < 150;
SELECT name,AVG(score) FROM t GROUP BY name HAVING AVG(score)>60 AND AVG(score)<90;
SELECT name,SUM(score),AVG(score) FROM t GROUP BY name HAVING AVG(score)<90 AND SUM(score)>150;
SELECT COUNT(*) n FROM (SELECT name,SUM(score),AVG(score) FROM t GROUP BY name HAVING AVG(score)<90 AND SUM(score)>150) n;
优化写法:
代码1:
SELECT
*
FROM
t;
代码2:
SELECT
NAME,
SUM(score)
FROM
t
GROUP BY
NAME
ORDER BY
SUM(score) DESC
LIMIT 1,
4;
代码3:
SELECT
NAME,
SUM(score)
FROM
t
GROUP BY
NAME
HAVING
SUM(score) < 150;
代码4:
SELECT
NAME,
AVG(score)
FROM
t
GROUP BY
NAME
HAVING
AVG(score) > 60
AND AVG(score) < 90;
代码5:
SELECT
NAME,
SUM(score),
AVG(score)
FROM
t
GROUP BY
NAME
HAVING
AVG(score) < 90
AND SUM(score) > 150;
代码6:
SELECT
COUNT(*) n
FROM
(
SELECT
NAME,
SUM(score),
AVG(score)
FROM
t
GROUP BY
NAME
HAVING
AVG(score) < 90
AND SUM(score) > 150
) n;
结果:
结果1:
结果2:
结果3:
结果4:
结果5:
结果6:
!!!注意:
1.having不能和order by 一起用。
2.
SELECT
COUNT(*) n
FROM
(
SELECT
NAME,
SUM(score),
AVG(score)
FROM
t
GROUP BY
NAME
HAVING
AVG(score) < 90
AND SUM(score) > 150
) n;
在上面的这个查询里,()部分外必须定义表别名m ,不然就报错,[Err] 1248 - Every derived table must have its own alias。
总结:
直接上书本上的公式,有权威性。
完毕。