关于mysql左连接的一些理解

通常我们左连接的时候,会觉得以左表为主,结果查出来的数据条数却比左表的少。原因很简单,因为表连接,你的where子句中加了右表的字段过滤。而有时候根据业务要求,我们需要显示所有的左表数据,怎样在不修改过滤条件的情况下,完全显示左表的所有行呢?这个时候,拿左表再去left join当前的表结果即可。例子如下

`SELECT ram.user_id as user_id,
IFNULL(A.last_days,0) ,
IFNULL(A.read_time,0),
ru.name as name,
ru.username as user_name,
ru.photo_url as photo_url

from r_activity_member ram   LEFT JOIN  
(
SELECT
				count(DISTINCT DATE_FORMAT(rar.end_time,'%Y/%m/%d')) as last_days,
                sum(rar.read_time)/60000 as read_time ,
                rar.user_id as user_id
                FROM
                 r_activity_member ram
								left join r_read_history rar on rar.user_id = ram.user_id
								LEFT JOIN r_user ru on ram.user_id = ru.id

                WHERE
                    rar.is_delete = 0 and ru.is_delete = 0 and ram.is_delete = 0

                    and rar.activity_id = '101'
                    AND (
                        rar.end_time
                        )  between '2019-03-01' and date_sub('2019-06-26', interval -1 day)
                    GROUP BY rar.user_id
                    having  sum(rar.read_time)/60000 >=3
                    order by sum(rar.read_time) desc
) A
on ram.user_id = A.user_id
LEFT JOIN r_user ru on ru.id = ram.user_id
where ram.is_delete = 0  and  ram.act_id = '101'
and ru.is_delete = 0`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值