數據庫查詢練習-簡單查詢練習及筆記(2)
1 分組計算平均成績
查詢每門課的平均成績;
select avg(degree) from score where cno='3-105';
#select avg(要求平均分的字段名稱) from 表名 where 根據那個字段求值='字段值';
/*
mysql> select avg(degree) from score where cno='3-105';
+-------------+
| avg(degree) |
+-------------+
| 85.3333 |
+-------------+
1 row in set (0.02 sec)
*/
如果數據量大 ,一次一次寫比較麻煩,所以用到分組;
select avg (degree) from score group by cno;
#select avg (要求平均分的字段名稱) from 表名 group by 根據那個字段來求;
/*
mysql> select avg (degree) from score group by cno;
+---------------+
| avg (degree) |
+---------------+
| 85.3333 |
| 76.3333 |
| 81.6667 |
+---------------+
3 rows in set (0.02 sec)
mysql> select cno, avg(degree) from score group by cno;
+-------+-------------+
| cno | avg(degree) |
+-------+-------------+
| 3-105 | 85.3333 |
| 3-245 | 76.3333 |
| 6-166 | 81.6667 |
+-------+-------------+
3 rows in set (0.02 sec)
*/
2 分組條件與模糊查詢
查詢 score
表中至少有 2 名學生選修,並以 3 開頭的課程的平均分數。
select cno from score group by cno having count(*)>=2 and cno like '3%';
#select 要查詢的字段 from 在那張表中查詢 group by 以哪個字段來分組 having count(*)>=條件 and 要模糊查詢的字段 like '模糊查詢的字符%';
# %表示模糊查詢通配符;
/*
mysql> select cno from score group by cno having count(*)>=2 and cno like '3%';
+-------+
| cno |
+-------+
| 3-105 |
| 3-245 |
+-------+
2 rows in set (0.03 sec)
*/
3 模糊查詢
通配符:
_表示任意一個字母 定長
%表示多個字母 不定長
select * from student where sbirthday like '1974%';
#select 那一個字段*表示所有 from 查那個表 where 模糊查詢的字段 like '模糊查詢的值%';
/*
mysql> select * from student where sbirthday like '1974%';
+-----+--------+------+---------------------+--------+
| sno | sname | ssex | sbirthday | sclass |
+-----+--------+------+---------------------+--------+
| 106 | 陸軍 | 男 | 1974-06-03 00:00:00 | 95031 |
| 109 | 趙鐵柱 | 男 | 1974-06-03 00:00:00 | 95031 |
+-----+--------+------+---------------------+--------+
2 rows in set (0.04 sec)
*/