mysql-组合查询

一、组合查询

  mysql允许执行多个查询(多条select语句),并将结果作为单个查询结果集返回。这些组合查询通常称为并(union)或复合查询(compound query)。

  有两种情况需要使用组合查询:

   1、在单个查询中从不同的表返回类似结构的数据。

   2、对单个表执行多个查询,按单个查询返回数据。

  可用Union操作符来组合数条sql查询,利用union,可给出多条select语句,将他们的结果组合成单个结果集。

二、使用union

  union使用比较简单,只是给出每条select 语句,在各条语句之间放上关键字UNION。

  如果我们需要价格小于等于5的所有物品的一个列表,而且还想包括供应商1001和1002生产的所有物品(不考虑价格)

  select vend_id,prod_id,prod_price from products where prod_price<=5 union select vend_id,prod_id,prod_price from products where vend_id in(1001,1002);

  以上两条语句的结果会通过union进行连接,组合成单个查询结果集。

  使用union可以代替where,并且能够完成由where非常复杂的结果,他比较简单的完成。

三、union规则

  1、union必须由两条或两条以上的select语句组成,语句之间用关键字Union分隔

  2、union中的每个查询必须包含相同的列、表达式或聚集函数。

  3、列数据类型必须兼容,类型不必完全相同,但必须是可以隐式转换。

    包含或取消重复的行:Union会从查询结果中自动去除了重复的行。这是union的默认行为,但是如果需要不取消重复行,我们使用union ALL而不是union,就可以实现效果,如下:  

    select vend_id ,prod_id,prod_price from products where prod_price<=5 union all select vend_id ,prod_id,prod_price from products where vend_id in(101,1002);

原文地址:https://www.cnblogs.com/television/p/8358596.html