转自:https://blog.csdn.net/xqd890608/article/details/50960403
1.
UNION ALL和
UNION 的区别
UNION ALL理论上要比
UNION的查询效率更高一些,因为
UNION会将结果集中的数据进行过滤,将相同的数据进行剔除后返回,而
UNION ALL不进行此操作,它会将结果集全部返回
2.UNION ALL分页要点
如果需要分页的时候只需要将他们联合查询的结果集当做一个表来查询就好了。
3.UNION ALL查询结果统计
- SELECT COUNT(*) FROM((SELECT id,money,createtime,status FROM pre_pay_log WHERE memb_id = 51225) UNION ALL (SELECT id,money,createtime,status FROM pre_cash_log WHERE memb_id = 51225))
此句查询会报错: Every derived table must have its own alias//每个派生出来的表都必须要有自己的别名
我们将sql语句改成下面,即可正常取值
- SELECT COUNT(*) FROM((SELECT id,money,createtime,status FROM pre_pay_log WHERE memb_id = 51225) UNION ALL (SELECT id,money,createtime,status FROM pre_cash_log WHERE memb_id = 51225)) as a
4. UNION ALL查询分页
- SELECT * FROM((SELECT id,money,createtime,status,error AS form_account,payment_no AS type_name FROM pre_pay_log WHERE 1 AND memb_id =51225) UNION ALL (SELECT id,money,createtime,status,form_account,type_name FROM pre_cash_log WHERE 1 AND memb_id =51225)) as a ORDER BY a.id DESC LIMIT 0,20
将合并查询后的语句派生出一个新的表后,我们就可以使用平常的分页操作进行分页了。