MySQL表连接 on and 和 on where 的区别

在使用left join时,on and和on where条件的区别如下:

  • on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
select *
from(select userID,DATE_FORMAT(paidTime,'%Y-%m-01') m from orderinfo
			where isPaid = '已支付'
			group by userID,DATE_FORMAT(paidTime,'%Y-%m-01')
			order by userID) t1
left join (select userID,DATE_FORMAT(paidTime,'%Y-%m-01') m from orderinfo
						where isPaid = '已支付'
						group by userID,DATE_FORMAT(paidTime,'%Y-%m-01')
						order by userID) t2
on t1.userID=t2.userID and t1.m = date_sub(t2.m,INTERVAL 1 month)

在这里插入图片描述

注:左连接中如果and语句是对左表进行过滤的,那么不管真假都不起任何作用。如果是对右表过滤的,那么左表所有记录都返回,右表筛选以后再与左表连接返回

  • where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
select *
from(select userID,DATE_FORMAT(paidTime,'%Y-%m-01') m from orderinfo
			where isPaid = '已支付'
			group by userID,DATE_FORMAT(paidTime,'%Y-%m-01')
			order by userID) t1
left join (select userID,DATE_FORMAT(paidTime,'%Y-%m-01') m from orderinfo
						where isPaid = '已支付'
						group by userID,DATE_FORMAT(paidTime,'%Y-%m-01')
						order by userID) t2
on t1.userID=t2.userID
where t1.m = date_sub(t2.m,INTERVAL 1 month)

在这里插入图片描述
产生的具体表现就是前者会存在null的完整版,而后者则只显示过滤出的数据

在使用inner join时,on and和on where条件区别如下:

  • on and 或者on where不管是对左表还是右表进行过滤,实际都是在生成临时表以后再进行过滤的,而且对左表和右表都起作用(故反映left join和inner join有本质区别)

参考连接:https://blog.csdn.net/echojson/article/details/80108921

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值