最近复习MYSQL,看到“union”这个一个关键词。书中写的很简单,网上查了半天,也觉得写的太笼统。
自己总结下吧。
1 对于目前项目来说,这种情况可以用到union:
比如我们有两个支付接口,一个是支付通,另外一个是汇付。支付通的资金记录(通过支付通通道的充值,提现,收款,还款等记录)存放在cd_account_history_a2里面;汇付的资金记录(通过汇付通道的充值,提现,收款,还款等记录)存放在cd_account_history_a3里面;
这样的话,两张表的结构是一致的,,即使不一致,我们也可以选取部分字段,用 union;
举例:查询用户id号是10715的支付通的资金记录:select * from cd_account_history_a2 where account_id=780;
查询用户id是10715的汇付的资金记录:select * from cd_account_history_a3 where user_id=10715;
将10715用户的所有资金记录联合起来:trac_id,amount,create_time 列字段显示:
select trac_id,amount,create_time from cd_account_history_a2 where account_id=780
union all select trac_id,amount,create_time from cd_account_history_a3 where user_id=10715;
如果显示出来的按照时间顺序排列:
可以有两种做法:
第一种: select * from (select trac_id,amount,create_time from cd_account_history_a2 where account_id=780
union all select trac_id,amount,create_time from cd_account_history_a3 where user_id=10715)a order by a.create_time ;
第二种 select trac_id,amount,create_time from cd_account_history_a2 where account_id=780
union all select trac_id,amount,create_time from cd_account_history_a3 where user_id=10715 order by create_time;(oder by 将前面那块看成一个整体,通常我们用第二种)备注:where不支持,group by支持;
2 另外一种情况,比如cd_user这张表存放的信息太多。我们要把之后的信息存放在cd_user1表里面,这样也用到 union;
3 两张表查询出来结果的叠加,也可以用union;
但是必须保证两张表查询的列数一致,列字段名一致(不一样的可以用别名代替,下面的例子user_real_name 用别名user_nick代替,跟第一张表中的名字保持一致 )
select user_nick from cd_user where id=10715 union
select user_real_name as user_nick from cd_user_infor where user_id=10715;
备注:其实3这种情况,我们通常通过两次查询即可。或者用in嵌套语句,这里只是举个例子,可以这样使用;
4 一张表里面用 union比较方便:
比如我们需要查询2种情况的组合数据:如果条件少,我们可以用or关键词,但是如果条件太多,我们就可以用到 union。。