mysql inner和union的用法及 union与unionall的区别

如 A ,B表
A中字段为 (Aid,username ,address);
B中字段为 (Bid,Aid,ObjType,name);

其中ObjType 中字段值为 S时候 表示发表,为 D 则为下载

如果只查询 S(发表)过的东西:

select A.*,count(Bid) from A join B on A.Aid=B.Aid where ObjType='S';


这其中:假如只有A join B,后面没跟on 限制条件的话,则会生成一个n*n的临时表,就好像,where A,B 一样
加上On 限制条件 只查询条件相同的结果集

如果想把 发表过和 下载过的 结果全部查出来的话,则考虑使用 union咯

   select A.username,count(Bid) as S,0 as D from A join B on A.Aid=B.Aid where ObjType='S'
union
select A.username,0 as S,count(Bid) as D from A join B on A.Aid=B.Aid where ObjType='D'

结果就为:
username S D
AA 2 0
AB 3 0
AA 0 3
AB 0 5


这样就把记录合并起来咯,但是AA的 S记录没有喝 D记录 放在同一行中

然后 在来一次查询
   select t.username,sum(t.S) as S sum(t.D)as D from (
select A.username,count(Bid) as S,0 as D from A join B on A.Aid=B.Aid where ObjType='S'
union
select A.username,0 as S,count(Bid) as D from A join B on A.Aid=B.Aid where ObjType='D' ) as t group by username;
结果就为:
username S D
AA 2 3
AB 3 5


其实用不考虑重复记录的话 用union all 速度会比 union 快一些

union :这个SQL在运行时先取出两个表的结果,再用排序空间进行排序删除重复的记录,最后返回结果集,如果表数据量大的话可能会导致用磁盘进行排序。
而union all只是简单的将两个结果合并后就返回。这样,如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据了。

使用 union 组合查询的结果集有两个最基本的规则:

1。所有查询中的列数和列的顺序必须相同。

2。数据类型必须兼容
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值