数据库命令的编写方法—3
1. 以b_student_score表为主,在后面加上b_subject_info表中的sub_name
select s.*,i.sub_name
from
b_student_score s left join b_subject_info i on i.id=s.sub_id
;
2. 把第一个插叙和第二个查询联合展示出来i
select
a.id,a.accont_name
from
b_user_info a
where a.class_id=1
union all
select
a.id,a.accont_name
from
b_user_info a
where a.class_id=2
;
注意:
- 两个查询结果字段个数必须相等
- 两个查询结果字段类型必须对应
- union all是全部合成,不会去掉重复
- union会去掉重复
3. 用distinct去掉重复
select distinct a.stu_id
from b_student_score a
;
4. 查询表b_user_info中重复的class_id;
select a.*
from
b_user_info a,
b_user_info b
where a.class_id=b.class_id and a.id<>b.id
;
运行方式:将表b_user_info当成两个表来查询,首先对比出class_id相等的部分,再对比出主键id不相等的部部分,去掉主键id向同的,取出主键id不同的,列出结果
5. case when then end 的用法
select a.id,a.class_id,
case a.class_id
when 1 then
'1班'
when 2 then
'2班'
else
'3班'
end ccc
from
b_user_info a
;
select a.id,a.class_id,
case when a.class_id<>1 then
'不是1班'
when a.class_id=2 then
'2班'
else
'x班'
end ccc
from
b_user_info a
;
case 后面跟条件,when后面也跟条件,进入相应的显示结果 ,但是不能同时使用两个条件