SQL25_查找山东大学或者性别为男生的信息

通过的代码

 

 
1
2
3
4
5
6
7
select device_id, gender, age, gpa
from user_profile
where university = '山东大学' 
union all
select device_id, gender, age, gpa
from user_profile
where gender = 'male' 

 

过程

    一开始是这样的
 
1
2
3
select device_id, gender, age, gpa
from user_profile
where university = '山东大学' or gender = 'male';
    运行,报错。说我的结果比预期结果少一条。我寻思默认不是不去重,去重得手动加distinct么?
    再次阅读题目,幸运地往下翻,幸运地看到灰色句子说先输出学校,再输出性别。这是union吧,union把两次查询的结果拼一起,先查学校,再查性别,把结果拼一起正好满足题目要求。union all表示不去重。运行,通过。
 
1
2
3
4
5
6
7
select device_id, gender, age, gpa
from user_profile
where university = '山东大学' 
union all
select device_id, gender, age, gpa
from user_profile
where gender = 'male' 

总结

如果不往下看,想不起来用union。
如果没练习过几次union,这题想几天也做不出来。
posted @ 2022-10-26 19:57  莫提默  阅读(47)  评论(0编辑  收藏  举报