sql常用

students表如下

id class_id name score
1 1 张三 33
2 1 李四 44
3 2 王二麻子 66
4 2 张强   75
5 3 赵四 43
6 3 刘能 88
7 4 谢广坤 98
8 4 刘大嘴 99
9 5 宋晓锋 92

class表如下

id class_name  
1 一年级    
2 二年级  
3 三年级  
4 四年级  
5 五年级  

基本查询

1.查询students表中所有数据:

select * from students

2.根据score倒叙排序:

select*from students order by score desc

3.根据score升序排序:

select*from students order by score asc

4.查询1-5条的数据:

SELECT * FROM students LIMIT 0,5

5.计算表中有多少条数据:

select count(*) from students

6.计算函数:sum / agv / min / max,可以直接嵌套

select sum(score) from students

多表查询

如果查询张三、李四是哪个班级,一张表就无法查看,可以直接进行多表查询

select students.name,class.class_name from students,class where students.id = class.id and students.name="张三","李四"

连接查询

左连接,取左边的表的全部,右边的表按条件,符合的显示,不符合则显示null

举例:select <select list> from A left join B on A.id=B.id

 

右连接:取右边的表的全部,左边的表按条件,符合的显示,不符合则显示null

举例:select <select list> from A right join B on A.id=B.id

 

内连接(inner join)
内连接:也称为等值连接,返回两张表都满足条件的部分

注释:inner join 就等于 join 

原文地址:https://www.cnblogs.com/ztcbug/p/12454720.html