一、语法区别:

1、select 字段 from 表格名称1 where 条件1 union/union all select 字段 from 表格名称2 where 条件2

注:a.表格1与表格2可以为同一个表格;

       b.需要去重的话用union,不需要去重的话,用union all

2、select 字段 from 表格名称 where 条件1 or 条件2

二、运行原理的区别:

1、union/union all:是先按照条件1把所有结果从表格1中选择出来,再按照条件2,从表格2中选择一遍(表格1与表格2可以为同一个表格),若需要去重,则选择用union,若不需要去重则选择union all.

2、or:在表格中从上到下检查是否符合条件1或2,若符合,则选择出来。

注:若表格1和表格2为相同的表格,则使用union和or的区别,从结果上来说,主要在于显示的数据的顺序。

三、例题:

现在运营想要分别查看学校为山东大学或者性别为男性的用户的device_id、gender、age和gpa数据,请取出相应结果,结果不去重。

示例:user_profile

id device_id gender age university gpa active_days_within_30 question_cnt answer_cnt
1 2138 male 21 北京大学 3.4 7 2 12
2 3214 male 复旦大学 4 15 5 25
3 6543 female 20 北京大学 3.2 12 3 30
4 2315 female 23 浙江大学 3.6 5 1 2
5 5432 male 25 山东大学 3.8 20 15 70
6 2131 male 28 山东大学 3.3 15 7 13
7 4321 male 28 复旦大学 3.6 9 6 52

根据示例,你的查询应返回以下结果(注意输出的顺序,先输出学校为山东大学再输出性别为男生的信息):

device_id gender age gpa
5432 male 25 3.8
2131 male 28 3.3
2138 male 21 3.4
3214 male None 4
5432 male 25 3.8
2131 male 28 3.3
4321 male 28 3.6

解答:1、输出的顺序,先输出学校为山东大学再输出性别为男生的信息,因此,用union all/union

           2、结果不去重,因此,用union all

elect device_id,gender,age,gpa
from user_profile
where university='山东大学' 
union all
select device_id,gender,age,gpa
from user_profile
where gender='male' 

Logo

展示您要展示的活动信息

更多推荐