在使用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