SQL 基本查询语句操作

最近笔试题目,总是碰到一些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。



总结:

直接上书本上的公式,有权威性。



完毕。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值