什么是 union 查询 ?
union 查询就是把 2 条或多条 sql 的查询结果 , 合并成 1 个结果集
sql1 返回 N 行
sql2 返回 M 行
sql1 union sql2 , 返回 N+M 行
1.、用 union 查询栏目 3 和栏目 4 下面的商品
- select goods_id,goods_name,cat_id,shop_price from goods where cat_id=3
- union
- select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4;
2.、查询网站用户 , 合并可以是两张相同的表 , 也可以是不同的表;
例如:用户表 user 和临时用户表 tmp;
- select uid,name from user
- union
- select id,name from tmp;
注意:
union 语句必须满足 1 个条件 ;各语句取出的列数必须相同;如果不相同 , 会报错;
3、union 查询有时候不一定返回的是不是 N+M 行;
例如:查 a 表和 b 表 ;应该是返回 9 条数据 , 但是只返回了 8 条数据 ;结果如下图:
- select * from a
- union
- select * from b;
注意 :
使用 union 时 , 完全相等的行 , 将会被合并 ,合并是比较耗时的操作 , 两行会在比较看是否完全相等,一半不让 union 进行合并 , 使用 "union all" 可以避免;在实际中 , 一般直接使用 union all 来合并查询,而不是用union;
4、union 的子句中 , 不用写 order by
- (select * from a order by num desc)
- union all
- (select * from b order by num desc);
运行以上sql语句,你会发现,order by 并没有发挥作用;这是因为每一条子句就算你排序了,但是合并以后的结果依然还是无序的;如果想对合并后的结果来排序,可以用order by;sql语句需要做一定的调整;以下是对合并后结果排序:
- (select * from a order by num desc)
- union all
- (select * from b order by num desc)
- order by num desc;