MySQL语法

2020-03-18  本文已影响0人  掩流年

GROUP BY

查询所有同学的学号,选课数,总成绩

select student_id, count(course_id),sum(score) 
from  score 
group by student_id
select s.student_id, stu.name, count(s.course_id),sum(s.score) 
from score s, student stu
where s.student_id = stu.student_id
group by s.student_id 

HAVING

select student_id ,avg(score)
from score
group by student_id
having avg(score) > 60

ORDER BY

ORDER BY子句中指定的列对上一步输出的虚拟表进行排列,返回新的虚拟表。还可以在ORDER BY子句中指定SELECT列表中列的序列号,如

select student_id , score 
from score
order by 2,1;

等同于

select student_id , score 
from score
order by score ,student_id ;

当然通常我们的用法是

ORDER BY create_time DESC;

LIMIT

应用LIMIT子句,表中选出从指定位置开始的指定行数据。对于没有应用ORDER BY的LIMIT子句,结果同样可能是无序的,因此LIMIT子句通常和ORDER BY子句一起使用。

LIMIT n, m

例如有表数据

//student1
student_id score
1     88
2     61
3     93
4     79
5     99
//student2
student_id score
1     43
2     68
3     91
4     71
6     65

left join

返回包括左表中的所有记录和右表中联结字段相等的记录

select * from student1
left join student2
on student1.student_id = student2.student_id
student_id score student_id(student2) score(student2)
1 88 1 43
2 61 68
3 93 3 91
4 79 4 71
5 99 null null

right join

返回包括右表中的所有记录和左表中联结字段相等的记录

select * from student1
right join student2
on student1.student_id = student2.student_id
student_id score student_id(student2) score(student2)
1 88 1 43
2 61 2 68
3 93 3 91
4 79 4 71
null null 6 65

inner join

只返回两个表中联结字段相等的行

select * from student1
inner join  student2
on student1.student_id = student2.student_id
student_id score student_id(student2) score(student2)
1 88 1 43
2 61 2 68
3 93 3 91
4 79 4 71
上一篇 下一篇

猜你喜欢

热点阅读