17:mysql union查询

什么是 union 查询 ?

union 查询就是把 2 条或多条 sql 的查询结果 , 合并成 1 个结果集

sql1 返回 N 行

sql2 返回 M 行

sql1 union sql2 , 返回 N+M 行

 

1.、用 union 查询栏目 3 和栏目 4 下面的商品

  1. select goods_id,goods_name,cat_id,shop_price from goods where cat_id=3
  2. union
  3. select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4;

 

2.、查询网站用户 , 合并可以是两张相同的表 , 也可以是不同的表;

例如:用户表 user 和临时用户表 tmp;

  1. select uid,name from user
  2. union
  3. select id,name from tmp;

 

注意:

union 语句必须满足 1 个条件 ;各语句取出的列数必须相同;如果不相同 , 会报错;

 

3、union 查询有时候不一定返回的是不是 N+M 行;

例如:查 a 表和 b 表 ;应该是返回 9 条数据 , 但是只返回了 8 条数据 ;结果如下图:

  1. select * from a
  2. union
  3. select * from b;

mysql union查询

注意 :

使用 union 时 , 完全相等的行 , 将会被合并 ,合并是比较耗时的操作 , 两行会在比较看是否完全相等,一半不让 union 进行合并 , 使用 "union all" 可以避免;在实际中 , 一般直接使用 union all 来合并查询,而不是用union;

 

4、union 的子句中 , 不用写 order by

  1. (select * from a order by num desc)
  2. union all
  3. (select * from b order by num desc);

运行以上sql语句,你会发现,order by 并没有发挥作用;这是因为每一条子句就算你排序了,但是合并以后的结果依然还是无序的;如果想对合并后的结果来排序,可以用order by;sql语句需要做一定的调整;以下是对合并后结果排序:

  1. (select * from a order by num desc)
  2. union all
  3. (select * from b order by num desc)
  4. order by num desc;
    A+
发布日期:2017年01月17日 22:30:24  所属分类:mysql教程
最后更新时间:2017-01-17 22:31:41
付杰
  • ¥ 68.0元
  • 市场价:128.0元
  • ¥ 199.0元
  • 市场价:199.0元
  • ¥ 299.0元
  • 市场价:599.0元
  • ¥ 79.0元
  • 市场价:99.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: