假设我们在数据库中有两张关联的表,一张叫做 students , 一张叫做 teachers ,两张表的具体内容如下。
students 表:
| stuid | name | sex | age | class | grade | tid | tname |
| 1 | 张一 | 男 | 8 | 1 | 3 | 1 | 李一 |
| 2 | 张二 | 女 | 7 | 2 | 2 | 2 | 王一 |
| 3 | 陈三 | 男 | 6 | 4 | 1 | 3 | 李一 |
| 4 | 李三 | 女 | 10 |
其中李三是新转来的学生,还没有分配班级
teachers表:
| tid | name | sex | class | grade |
| 1 | 李一 | 男 | 5 | 3 |
| 2 | 王一 | 男 | 3 | 1 |
| 3 | 李一 | 女 | 2 | 2 |
| 4 | 刘二 | 女 |
其中刘二是新来的老师,还没有分配班级。
以下就用这两张表作为例子。
一、创建表
create table students(stuid int(4) not null,name varchar(4) not null,age int(2),sex char(2),class char(3),grade char(2),tid int,tname char(10),primary key (stuid),foreign key (tid) references teachers (id));
create table teachers(tid int(4) not null,name varchar(4) not null,sex char(2),class char(3),grade char(2),primary key (tid));
二、更新表
插入新数据
# insert intoinsert into students (stuid,name,sex,age) values (4,'李三','女',10);
修改数据
update students set name='李四' where stuid=4;
三、查询数据
sql查询中最简单的是查询整张表:
select * from students;
如果需要加入查询条件,则在后面加上 where 语句
1.在where条件中可以使用的等式有:
# 等于 = / 不等于 <> / 大于 > / 大于等于 >= / 小于 < / 小于等于 <=# 如 查询名字为“张一”的学生select * from students where name = "张一";# between .. and .. 查询某个区间范围# 如 查询1-2年级的学生信息select * from students where grade between 1 and 2;# like 模糊查询# 如 查询姓张的学生select * from students where name like "张%";# in 查询某个集合# 如 查询李一老师和王一老师的学生select * from students where teacher in ("李一","王一");
在上面的语句中,第9行中的 '%' 是一个通配符,常用的通配符有:
%:替代0个或多个字符_:替代1个字符[char]:字符列中任何单一字符[^char]:不在字符列中的任何单一字符
2.需要将多张表联合起来查询
# join# 如 查询学生与老师的对应关系(不包含新来的学生与老师)select students.name,teachers.name from students join teachers on students.tname = teachers.name;# left join 左连接,保留左表中的内容# 如 查询所有学生及他们对应的老师的名字select students.name,teachers.name from students left join teachers on students.tname = teachers.name;# right join 右连接,保留右表中的内容# 如 查询所有老师及他们所教的学生名字select students.name,teachers.name from students right join teachers on students.tname = teachers.name;# union 合并多个结果集,并去掉重复值select tname from students union select name from teachers;# union all 保留重复值
3.对结果进行过滤
# distinct# 查询已经分配了班级的老师名字select distinct tid,tname from students;# order by 排序,默认升序(ASC),降序为DESC# 查询学生名字,按年级降序排序select name,grade from students order by grade desc;# group by 对一列或多列结果集进行分组# as
4. sql语句中常用的函数
# 求平均值avg()# 求行数count()# 返回第一个记录的值first()# 返回最后一个记录的值last()# 返回最大值max()# 返回最小值min()# 返回和sum()# 筛选分组后的数据having# 将字段的值转换为大写/小写ucase()lcase()# 返回当前系统的日期和时间now()# 对字段进行格式化format()# 返回子字符串在字符串中的位置position(substring in str)
部分地方写得有些粗糙,后续再进行细化。

最后修改时间:2019-12-16 10:37:10
文章转载自我和软件测试,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




